简体   繁体   English

在JavaScript中的字符串上调用forEach

[英]Call forEach on a string in JavaScript

I am not that experienced in JS so maybe this is a very naive question. 我没有JS方面的经验,所以也许这是一个非常幼稚的问题。 I tried to call 我试图打电话

"".forEach((e, i) => {
    console.log(e)
})

And I get an error saying that forEach is not a function for a string. 而且我得到一个错误,说forEach不是字符串的函数。 Yet when I call: 但是当我打电话时:

Object.getOwnProperyNames("")

I can clearly see that forEach() is in the prototype of the string and of type function . 我可以清楚地看到forEach()在字符串和type function的原型中。

Why can I not call it on a string? 为什么不能在字符串上调用它?

Object.getOwnPropertyNames returns an array, and you can iterate through an array - no surprises there. Object.getOwnPropertyNames返回一个数组,您可以遍历一个数组-在那里没有惊喜。

As for iterating through a string with a forEach loop, you can't - you can only use a for loop. 至于使用forEach循环遍历字符串,则不能-只能使用for循环。 That is, iterating through a string . 也就是说,遍历string A quick and easy way to use forEach is to spread the string into an array: 使用forEach一种快速简便的方法是将字符串分布到数组中:

[..."Hello, World!"].forEach((e, i) => console.log(e));

Or, if it contains certain characters: 或者,如果它包含某些字符:

Array.from("Hello, World!").forEach((e, i) => console.log(e));

Object.getOwnPropertyNames("") only returns ["length"] . Object.getOwnPropertyNames("")仅返回["length"] The .foreach you're seeing, I assume in Inspector, is a property of the array returned (ie. you could call ["length"].foreach(...) ). 我在Inspector中假设您所看到的.foreach是返回数组的属性(即,您可以调用["length"].foreach(...) )。 It does not imply that string has a foreach method. 这并不意味着该字符串具有foreach方法。

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

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