gpt4 book ai didi

javascript - 替换特定索引(数组)处的值

转载 作者:行者123 更新时间:2023-12-04 01:49:31 29 4
gpt4 key购买 nike

大家晚上好

我有一个包含 24 个字符的数组

"hours": [
"1",
"1",
"1",
"1",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0"
]

我想搜索另一个索引数组;例如 [2, 5, 9, 10]

然后,转到第一个数组的(第一个数组的)位置(2、5、9和10)并将字符更改为该位置的“1”,并将数组的其余部分移动到“0"

有人可以指导我吗?

谢谢!

最佳答案

解决方案:

var hours = ["1", "1", "1", "1", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"],
positions = [2, 5, 9, 10];

for (var i = 0; i < hours.length; i++) {
hours[i] = positions.includes(i) ? "1" : "0";
}

console.log(hours);

// ["0", "0", "1", "0", "0", "1", "0", "0", "0", "1", "1", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"]

演示: https://jsfiddle.net/gzynud0c/1/


As pointed out in the comments, the above solution works in all major browsers, including IE9+, without using a transpiler like Babel or using a polyfill.

以下适用于所有浏览器。

for (var i = 0; i < hours.length; i++) {
hours[i] = ~positions.indexOf(i) ? "1" : "0";
}

演示: https://jsfiddle.net/s59jt870/3/

关于javascript - 替换特定索引(数组)处的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51921107/

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