[英]Why can't / shouldn't I use a while loop to monitor asynchronous jQuery operations?
[英]Why can't I use an array as the 'specified condition' in a while loop?
所以我有這個代碼:
var myArray = [];
var value = 5;
while (myArray != [5, 4, 3, 2, 1, 0]) {
myArray.push(value)
value--;
console.log(myArray);
}
當我查看控制台時,它會像這樣進行無限循環..
[ 5 ]
[ 5, 4 ]
[ 5, 4, 3 ]
[ 5, 4, 3, 2 ]
[ 5, 4, 3, 2, 1 ]
[ 5, 4, 3, 2, 1, 0 ]
[ 5, 4, 3, 2, 1, 0, -1 ]
[ 5, 4, 3, 2, 1, 0, -1, -2 ]
[ 5, 4, 3, 2, 1, 0, -1, -2, -3 ]
…………
為什么它不在 [5,4,3,2,1,0] 處停止? myArray = 在某個點上,for 循環應該停止嗎?
對不起菜鳥問題。
JavaScript 不提供對 Arrays 的結構相等性的內置支持,但實現比較器很簡單:
function arraysEqual(a, b, orderSensitive = true) {
// Function from https://stackoverflow.com/a/16436975/159145
// But modified to add the `orderSensitive` option.
if (a === b) return true;
if (a == null || b == null) return false;
if (a.length != b.length) return false;
if (!orderSensitive) {
a = Array.from(a).sort();
b = Array.from(b).sort();
}
for (var i = 0; i < a.length; ++i) {
if (a[i] !== b[i]) return false;
}
return true;
}
function yourCode() {
var myArray = [];
var value = 5;
const finalArray = [5, 4, 3, 2, 1, 0];
while (!arraysEqual(myArray,finalArray)) {
myArray.push(value)
value--;
console.log(myArray);
}
}
如果 arrays 的索引和值不同,您可以使用以下方法解決問題
while(sortArray(myArray).toString() !== sortArray([5, 4, 3, 2, 1, 0]).toString()) {
// your code
}
sortArray(array) {
return array.filter((a, b) => a-b)
}
如果您確定 arrays 的數組索引和值相同,您可以使用
while(myArray.toString() !== [5, 4, 3, 2, 1, 0].toString()) {
// your code
}
@Christopher Barreto,歡迎來到 StackOverflow。 祝你有趣的問題好運。
盡管@Dai 的完整答案是正確的,但是將數組轉換為字符串然后進行比較的方法要簡單得多。
這對你有用:
var myArray = [];
var value = 5;
while (myArray.toString() != [5, 4, 3, 2, 1, 0].toString()) {
myArray.push(value)
value--;
console.log(myArray);
}
或者,如果您願意,可以這樣做:
while ((''+myArray) != ('' + [5, 4, 3, 2, 1, 0]))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.