将函数结果存储到变量中

Store function result to variable

本文关键字:变量 存储 函数 结果      更新时间:2023-09-26

如何将函数的结果存储到变量?

在导航一个包含数组的对象时,我正在寻找一个值value1,一旦找到,我想获得它的一个属性的值property1

我下面使用的代码是一个示例,是不正确的。

function loadSets(id){
   clworks.containers.find(function(i){
      return i.get('property1')===id;
   });
}

我的目的是导航下面的对象:

clworks.containers
    containers[0].property0.id
    containers[1].property1.id

我试图确定如何在数组中找到哪个项目具有等于函数中使用的id的属性值,然后将其存储为变量。

简体:

var myVar = loadSets(id);

编辑

好的,就我现在了解你的问题而言,你的情况如下:

  1. 你有一个array包含对象称为containers;
  2. 您要遍历这个array,查找属性property1的属性id,该属性等于函数loadSets(id)中指定的属性;
  3. 一旦找到,将具有请求的id的对象存储在变量中。

我说的对吗?如果是这样,应该可以解决您的问题:

// This function iterates through your array and returns the object
// with the property id of property1 matching the argument id
function loadSets( id ) {
    for(i=0; i < containers.length; i++) {
        if( containers[i].property1.id === id )
            return containers[i];
    }
    return false;
}
在这之后,你只需要做我在你的问题的第一个答案中所说的,触发它,但你想要的。我为你设置了一个快速JSBin 。尝试将10或20放在input字段中,然后点击查找按钮;它将返回您正在查找的对象。尝试输入任何其他数字,它将返回一个Not found

目前你的函数loadSets实际上没有返回任何东西,所以你不能存储它的结果。

试题:

function loadSets(id){
   return Base.containers.find(function(i){
      return i.get('entityid')===id;
   });
}

以及将结果放入变量:

var result = loadSets(id);