gpt4 book ai didi

javascript - 抓取数组的一个元素

转载 作者:行者123 更新时间:2023-12-03 04:29:05 25 4
gpt4 key购买 nike

var input = prompt();
var binput = input.split("");
var inputl = input.split(" ").length

if ( inputl % 5 == 0 ) {
binput.forEach(function(v, i) {
if (v === "a") {
binput[i] = "$"
}
})
}

我的问题是,我只想更改 inputl 的第 5 个、第 10 个、第 15 个...元素,现在它更改了整个文本 if (inputl % 5 == 0) 。但是我只想获取 inputl 数组的第五个元素。

最佳答案

my problem here is that i want only the 5th 10th 15th

试试这个

binput.forEach(function(v, i) { //iterate once
if( (i + 1 ) % 5 == 0) //check if the element is 5th, 10th, 15th etc
{
binput[i] = "$"; //assign the value as you like
}
}};

编辑:

如果您还想在分配新值之前检查该值是否为“a”,请尝试

binput.forEach(function(v, i) { //iterate once
if( v == "a" && ( (i + 1 ) % 5 == 0 ) ) //check if the element is 5th, 10th, 15th etc
{
binput[i] = "$"; //assign the value as you like
}
}};

关于javascript - 抓取数组的一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43569235/

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