gpt4 book ai didi

javascript - for 循环内的 if 语句 - 不满足条件

转载 作者:行者123 更新时间:2023-12-03 12:39:23 24 4
gpt4 key购买 nike

var text = [["1","1.","The Wagner diatribe and 'The Twilight of the Idols' were published"],["2","2.","suspect that the delay was due to the influence of the philosopher's"],["3","3.","bounds were marked by crosses. One notes, in her biography of him--a"]];

var amountOfTexts = text.length;
var tempArray = [];
for(var i=0; i<amountOfTexts; i++){
tempArray = [];
var current = text[i][2];
var x = current.length;
for(var j=0; j<x; j++){
var y = j+1;
if(current.substr(j,y) === " "){
tempArray.push("counter");
}
}
console.log(tempArray.length);
var nearlyWords = tempArray.length;
var words = 1+nearlyWords;
text[i].push(words);
}

这会打印到控制台:

0
0
1

我期待的地方:

11
12
12

它的意思是把te​​xt[i][2]中字符串的字数推到text[i][3]。

我已经检查过了,最接近的是问题是 if 语句的条件...但它们看起来很好。

问题:为什么它不起作用?

最佳答案

您使用的 substr 方法是错误的,它采用的参数与 substring 方法不同。

使用substr并指定长度作为第二个参数:

if (current.substr(j, 1) === " ") {

或将substring与您当前的参数一起使用:

if (current.substring(j, y) === " ") {

您还可以使用charAt方法来获取字符,这看起来更自然:

if (current.charAt(j) === " ") {

在较新的浏览器(IE 8 及更高版本)中,您还可以使用括号语法获取字符:

if (current[j] === " ") {

关于javascript - for 循环内的 if 语句 - 不满足条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23584991/

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