gpt4 book ai didi

Javascript 检查数组的元素

转载 作者:行者123 更新时间:2023-11-30 17:10:07 26 4
gpt4 key购买 nike

如果一个数组的元素除一个为 1 之外全为 0,我如何检查它?

示例:

array = [0, 0, 0, 1, 0];
check(array); //returns the index where it is 1 which is 3

array = [0, 3, 0, 2, 0];
check(array); //returns -1

array = [0, 3, 1, 2, 0];
check(array); //returns -1 again if there are non zero aside from 1, it should be one 1 and others are all 0.

array = [0, 0, 1, 0, 1];
check(array); //returns -1 again, there should just be one element of 1

最佳答案

function check(a) {
var index = -1;
for (var i = 0; i < a.length; i++) {
if (a[i] == 1) {
if (index < 0) {
index = i;
} else {
return -1;
}
} else if (a[i] != 0) {
return -1;
}
}
return index;
}

array1 = [0, 0, 0, 1, 0];
check(array1); //returns 3

array2 = [0, 3, 0, 2, 0];
check(array2); //returns -1

关于Javascript 检查数组的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27199053/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com