正如我們所知.forEach(),JavaScript 中有一種用于陣列的方法。但是字串沒有內置該方法。
那么,有沒有關于下面的代碼片段的任何問題:
String.prototype.forEach = Array.prototype.forEach?
此設定可幫助我.forEach用于字串。
let myName = "Avetik";
String.prototype.forEach = Array.prototype.forEach;
myName.forEach(char => {
console.log(char);
})
上面的代碼作業正常并輸出我名字的所有字符。
你已經猜到我是 JS 的新手了。
uj5u.com熱心網友回復:
你可以,但是:
- 這很令人困惑(其他開發人員在同一代碼庫上作業時看到這樣一個在字串上呼叫的方法很可能會非常困惑)
- 可能導致代碼脆弱(如果您定義
String.prototype.forEach,它可能會干擾其他使用 String 原型上的方法的代碼) - 幫助不大:你可以
[...str].forEach很輕松地做,也可以for (const char of str) {很輕松地做
顯示代碼片段
// Say we want to iterate over this string:
const str = 'str';
// without adding a method to the prototype. Easy:
// One method:
for (const char of str) {
console.log(char);
}
// Another method:
[...str].forEach((char) => {
console.log(char);
});
- 如果足夠多的腳本撰寫者定義了這樣的東西,可能會破壞語言的未來語法(看看
Array.prototype.contains和發生了什么Array.prototype.flatten)
所以,這是可行的,但這可能不是一個好主意。
uj5u.com熱心網友回復:
您可以添加自己的包裝器...
我幾乎無法抗拒這些壞主意!
我的建議是,去做,然后等待那一天,否則這樣的做法會對你不利。那么你就會有這樣一個錯誤的衡量標準,我希望這肯定會阻止你玩語言語法,如果幸運的話,你可能會成為一名計算機語言大師。
if(typeof String.prototype.forEach !== "function") {
String.prototype.forEach = Array.from(this).forEach
};
// sample usage :
let abc = 'abc'
abc.forEach((letter, index)=> console.log(letter,index))
但最好使用一個不那么模糊的名字
if(typeof String.prototype.forEachLetter !== "function") {
String.prototype.forEachLetter = Array.from(this).forEach
};
// sample usage :
let abc = 'abc'
abc.forEachLetter((letter, index)=> console.log(letter,index))
uj5u.com熱心網友回復:
.forEach() 本質上是一個用于陣列(多個事物的組)的函式。一個字串只是一件事,當只有 1 時,就沒有辦法為“每個”做一些事情。
您可以在字串上使用.split()將其轉換為包含每個字符的陣列。然后對結果執行任何您想要的陣列操作。如果需要,然后在陣列上使用.join()將其轉換回字串。
var myString = "beans";
var myArray = myString.split(); // this will be an array of 5 strings: ['b', 'e', 'a', 'n', 's']
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/356546.html
標籤:javascript 数组 细绳 foreach
上一篇:將短語拆分為多維字符陣列
