我如何通过一个序列中的所有输入,使用JavaScript?


当前回答

// 使用前端 ECMAScript 6 路径通过 路径 路径 路径 路径 路径 路径 路径 路径 路径 路径 路径 路径 路径 路径 路径 路径 路径 路径 路径 路径

其他回答

您可以使用图书馆获得此功能(我建议 Underscore.js),使用一个简单的在路径。

for (var instance in objects) {
   ...
}

但是,请注意,可能有理由使用一个更简单的旋转(见 Stack Overflow 问题 为什么使用“为”与序列调节这样的坏想法?)

var instance;
for (var i=0; i < objects.length; i++) {
    var instance = objects[i];
    ...
}

没有内置的能力打破 forEach. 要停止执行,请使用 Array#some 如下:

[1,2,3].some(function(number) {
    return number === 1;
});

這是因為有些回來是真實的,一旦任何的呼叫回來,執行在順序,回來是真實的,短循環的執行的其他。

假设我们有几个主题:

let ddl = new Array();
if (subjects) {
    subjects.forEach(function (s) {ddl.push({"id": s.id, "label": s.name});});
}

ECMAScript 5(JavaScript版本)与Arrays一起工作:

forEach - 通过序列中的每个项目,并与每个项目所需的一切。

['C', 'D', 'E'].forEach(function(element, index) {
  console.log(element + " is #" + (index+1) + " in the musical scale");
});

// Output
// C is the #1 in musical scale
// D is the #2 in musical scale
// E is the #3 in musical scale

在这种情况下,更有兴趣使用一些内置功能在序列上运行。

地图 - 它创建一个新的序列,结果是呼叫回复功能. 这个方法是很好的使用,当你需要格式化的元素的序列。

// Let's upper case the items in the array
['bob', 'joe', 'jen'].map(function(elem) {
  return elem.toUpperCase();
});

// Output: ['BOB', 'JOE', 'JEN']

减少 - 正如名称所说,它将序列减少到一个单一值,通过在当前元素中传输的特定函数和以前的执行结果。

[1,2,3,4].reduce(function(previous, current) {
  return previous + current;
});
// Output: 10
// 1st iteration: previous=1, current=2 => result=3
// 2nd iteration: previous=3, current=3 => result=6
// 3rd iteration: previous=6, current=4 => result=10

每次 - 返回真实或虚假,如果序列中的所有元素在呼叫回复函数中通过测试。

// Check if everybody has 18 years old of more.
var ages = [30, 43, 18, 5];
ages.every(function(elem) {
  return elem >= 18;
});

// Output: false

过滤器 - 非常相似于每一个,除了过滤器返回一个序列的元素返回真实的给定的功能。

// Finding the even numbers
[1,2,3,4,5,6].filter(function(elem){
  return (elem % 2 == 0)
});

// Output: [2,4,6]

Iterators 提高效率,让您同时消耗列表中的物品,就好像它们是流。 使 iterator 特别的是它通过收藏的方式. 其他插槽需要将整个收藏上传到前面,以便在收藏中进行 iterate,而 iterator 只需要知道收藏中的当前位置。

您可以通过呼叫 iterator 的下一个方法访问当前项目,下一个方法将返回当前项目的值,并将一个 boolean 指示您到达收藏结束时。

您也可以使用 Symbol.iterator 将您的常规序列转换为 iterator 如下:

您也可以将您的常规序列转换为这样的 iterator:

注意事项:

对象不默认可用,在这种情况下使用为..in,因为而不是值,它用钥匙工作。