我如何通过一个序列中的所有输入,使用JavaScript?
当前回答
没有内置的能力打破 forEach. 要停止执行,请使用 Array#some 如下:
[1,2,3].some(function(number) {
return number === 1;
});
這是因為有些回來是真實的,一旦任何的呼叫回來,執行在順序,回來是真實的,短循環的執行的其他。
其他回答
var 语言 = [“Java”,“JavaScript”,“C#”,“Python”]; var i, len, 文本; for (i = 0, len = languages.length, text = “”; i < len; i++) { 文本 += 语言[i] + “<br>”; } document.getElementById(“例子”)。innerHTML = 文本; <p id="例子"></p>
var text = "; var i = 0; while (i < 10) { text += i + ") something<br>; i++; } document.getElementById("example").innerHTML = text; <p id="example"></p>
功能滑板 - forEach,地图,过滤器,也减少(它们滑板通过功能,但它们是使用的,如果你需要做一些与你的序列,等等。
根据新更新 ECMAScript 6 (ES6) 和 ECMAScript 2015 的功能,您可以使用以下选项:
对于洛普
for(var i = 0; i < 5; i++){
console.log(i);
}
// Output: 0,1,2,3,4
上一篇:在洛普斯
let obj = {"a":1, "b":2}
for(let k in obj){
console.log(k)
}
// Output: a,b
Array.forEach( )
let array = [1,2,3,4]
array.forEach((x) => {
console.log(x);
})
// Output: 1,2,3,4
為...LOPS
let array = [1,2,3,4]
for(let x of array){
console.log(x);
}
// Output: 1,2,3,4
當LOPS
let x = 0
while(x < 5){
console.log(x)
x++
}
// Output: 1,2,3,4
此分類上一篇: while loops
let x = 0
do{
console.log(x)
x++
}while(x < 5)
// Output: 1,2,3,4
使用到...可能的地方
async /await support |
Skips non-numeric props | Immutable index | |
---|---|---|---|
for...of |
✅ | ✅ | ✅ |
forEach() |
❌ | ✅ | ✅ |
for...in |
✅ | ❌ | ✅ |
Regular for |
✅ | ✅ | ❌ |
正如上面的表中可以看到的那样,它应该随时随地使用,因为它支持非同步功能,并通过随机修改曲线指数来阻止非数字特性。
合成
const nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
for (const num of nums) {
/* Do something with num */
}
查看更多例子的参考,链接到规格和与与与与与之间的差异,或者可能检查这个教程,以了解它们如何不同。
某些 C 风格的语言使用 foreach 通过列表旋转。 在 JavaScript 中,这与 for..in 旋转结构进行:
var index,
value;
for (index in obj) {
value = obj[index];
}
要避免通过对象的原型继承的阅读值,只需检查是否属于对象的财产:
for (i in obj) {
if (obj.hasOwnProperty(i)) {
//do stuff
}
}
此外,ECMAScript 5 已添加一个 forEach 方法到 Array.prototype 可以用来列出一个序列,使用一个字符串(多字符串在文件中,所以你仍然可以使用它在更老的浏览器):
arr.forEach(function (val, index, theArray) {
//do stuff
});
重要的是要注意的是,当通话返回虚假时,Array.prototype.forEach 不会破裂。 jQuery 和 Underscore.js 提供各自的变量,以提供可以短循环的漏洞。
// 使用前端 ECMAScript 6 路径通过 路径 路径 路径 路径 路径 路径 路径 路径 路径 路径 路径 路径 路径 路径 路径 路径 路径 路径 路径 路径