简体   繁体   English

如何将前一项附加到数组中的下一项?

[英]How to attach the previous item to the next in array?

I want to add the previous value to each array item except the first one Use the following code,result is true.input is ['python','jieba'],output is [ 'python', 'python jieba' ] 我想为除第一个数组之外的每个数组项添加上一个值使用以下代码,结果为true。input为['python','jieba'],输出为['python','python jieba']

var config={keywords: ['python','jieba']}
var keywords=config.keywords
for(keyword in keywords){

 if (keyword==0){

 }
 else{
    keywords[keyword]=keywords[keyword-1]+" "+keywords[keyword]
    console.log(keywords)
 }
}

But if I use an if statement,the code like this: 但是,如果我使用if语句,则代码如下:

var config={keywords: ['python','jieba']}
var keywords=config.keywords
for(keyword in keywords){

 if (keyword!==0){

    keywords[keyword]=keywords[keyword-1]+" "+keywords[keyword]
    console.log(keywords)
 }

}

The return is wrong, 退货是错误的,

[ 'undefined python', 'jieba' ]
[ 'undefined python', 'undefined python jieba' ]

Is the if statement incorrectly written? if语句写错了吗?

This sounds like a job for reduce : 听起来这是reduce的工作:

 var keywords = ['python', 'jieba']; keywords.reduce((a, b, i) => keywords[i] = `${a} ${b}`); console.log(keywords); 

Of course, if you only want to get the final result (all the keywords combined together), just use join : 当然,如果只想获得最终结果(所有关键字组合在一起),只需使用join

 var keywords = ['python', 'jieba']; var joinedKeywords = keywords.join(' '); console.log(joinedKeywords); 

The key is a string. 关键是一个字符串。

You need to take 你需要带

if (keyword != 0) {

or better 或更好

if (keyword !== '0') {

 var config = { keywords: ['python', 'jieba'] }, keywords = config.keywords, keyword; for (keyword in keywords) { if (keyword !== '0') { keywords[keyword] = keywords[keyword - 1] + " " + keywords[keyword] console.log(keywords) } } 

You are comparing a String to a Number. 您正在将字符串与数字进行比较。 change your condition to if (keyword!=='0') . 将条件更改为if (keyword!=='0') And you are trying to access an index that does not exist when first calling keywords[keyword-1] . 并且您尝试访问的是在首次调用keywords[keyword-1]时不存在的索引。

Also, I do not recommend to use for...in in your case, but rather a simple for loop or more advanced solution using Array.reduce (see the answer by @pswg). 另外,我不建议在您的情况下使用for...in ,而是使用Array.reduce进行简单的for循环或更高级的解决方案(请参阅@pswg的答案)。 I quote the MDN for...in entry: 条目中引用MDN 作为...

Array indexes are just enumerable properties with integer names and are otherwise identical to general object properties. 数组索引只是具有整数名称的可枚举属性,其他方面与常规对象属性相同。 There is no guarantee that for...in will return the indexes in any particular order. 不能保证for ... in将以任何特定顺序返回索引。 The for...in loop statement will return all enumerable properties, including those with non–integer names and those that are inherited. for ... in循环语句将返回所有可枚举的属性,包括那些具有非整数名称和被继承的属性。

Because the order of iteration is implementation-dependent, iterating over an array may not visit elements in a consistent order. 因为迭代的顺序与实现有关,所以在数组上进行迭代可能不会以一致的顺序访问元素。 Therefore, it is better to use a for loop with a numeric index (or Array.prototype.forEach() or the for...of loop) when iterating over arrays where the order of access is important. 因此,在访问顺序很重要的数组上进行迭代时,最好使用带有数字索引的for循环(或Array.prototype.forEach()或for ... of循环)。

 var config = { keywords: ['python', 'jieba'] } var keywords = config.keywords for (var i = 1; i < keywords.length; i++) { // starting with i=0 would try to access keywords[0 - 1] which results in undefined if (keywords[i] != 0) { keywords[i] = keywords[i - 1] + " " + keywords[i] console.log(keywords) } } 

Consider switching to a traditional for loop using an index instead of for-in: 考虑使用索引而不是for-in切换到传统的for循环:

 var config = {keywords: ['python', 'jieba']}; var keywords = config.keywords; for (var i = 1; i < keywords.length; i++) { keywords[i] = keywords[i - 1] + " " + keywords[i]; console.log(keywords); } 

I think it's regrettable that you accepted Nina's answer because she skips an important point and this omission can be misleading. 我很遗憾您接受Nina的回答,因为她跳过了重点,而这种疏忽可能会引起误解。 Consider reading this answer again, it was the most enlightening in my opinion: https://stackoverflow.com/a/54700039/1636522 . 考虑再次阅读此答案,这是我认为最有启发性的内容: https : //stackoverflow.com/a/54700039/1636522 The quote from MDN tells us that iterating over an array with a for...in loop is a bad idea for two reasons. MDN报价告诉我们,使用for...in循环遍历数组是一个坏主意,原因有两个。 The first one is obvious with an example: 第一个例子很明显:

> | xs = ["a"]
< | ["a"]
> | for (i in xs) console.log(i, xs[i])
  | 0 a
> | xs["a"] = 0
< | 0
> | for (i in xs) console.log(i, xs[i])
  | 0 a
  | a 0

Sad, and this is not a bug :-\\ Indeed, for...in is meant to iterate over enumerable properties, and indexes are only a part of it. 遗憾的是,这不是bug:-\\确实, for...in旨在迭代可枚举的属性,而索引只是其中的一部分。

> | Object.keys(xs) // returns enumerable properties
< | ["0", "a"]

The second reason is that for...in may not visit elements in consistent order. 第二个原因是for...in可能不会以一致的顺序访问元素。 Most of the time everything works as expected, but someday you could observe a weird behaviour like this: 大多数时候,一切都会按预期进行,但是总有一天,您会观察到如下奇怪的行为:

> | xs = ["a", "b"]
< | ["a", "b"]
> | for (i in xs) console.log(i, xs[i])
  | 1 b
  | 0 a

Again, this is not a bug. 同样,这不是错误。 Since properties are not always indexes, there is no reason to visit them in a specific order. 由于属性并不总是索引,因此没有理由按特定顺序访问它们。 It could be harmful considering your requirements. 考虑到您的要求,这可能是有害的。 Indeed, push one more element to the array and your algorithm is likely to have unpredictable behaviour: 确实,将另一个元素推到数组中,您的算法可能会有不可预测的行为:

> | xs = ["python", "jieba", "more"]
< | ["python", "jieba", "more"]
> | for (i in xs) {
  |   if (i !== "0") xs[i] = xs[i - 1] + " " + xs[i];
  |   console.log(i, xs[i]);
  | }
  | xs

The above code may produce the expected trace: 上面的代码可能会产生预期的跟踪:

  | 0 python
  | 1 python jieba
  | 2 python jieba more
< | ["python", "python jieba", "python jieba more"]

But it may also produce something unexpected like this: 但它也可能会产生以下意外情况:

  | 2 jieba more
  | 0 python
  | 1 python jieba
< | ["python", "python jieba", "jieba more"]

Now I hope this is clear for you that using for...in to iterate over an array is a bad habit. 现在,我希望这对您很清楚,使用for...in遍历数组是一个坏习惯。 You should better switch to either a good old for loop or a for...of loop: 您最好切换到旧的for循环或for...of循环:

> | for (i = 0; i < xs.length; i++) console.log(i, xs[i])
  | 0 "a"
> | for (x of xs) console.log(x)
  | a

Finally, let's get to the bottom of the question. 最后,让我们深入问题的底部。 Why keyword != 0 works while keyword !== 0 fails? 为什么keyword != 0 keyword !== 0无效而keyword !== 0无效? Keep in mind that for...in is looking for object keys, and a key is a string. 请记住, for...in正在寻找对象键,而键是字符串。 Now look: 现在看:

> | "0" != 0 // normal equality with type conversion
< | false
> | "0" !== 0 // strict equality with type comparison
< | true

Got it? 得到它了? A key is not a number :-) 键不是数字:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM