簡體   English   中英

如何在JavaScript中循環遍歷數組

[英]How to Loop Through ths Array in JavaScript

我是Javascript的新手,我開始學習。

我需要幫助理解; 如何檢索此數組的每個carachter。

var possibleRaysPasswords =['mobleyAndTrentonAreDead','tyrellIsElliot','dreadPirateRoberts'];

就像這些例子中一樣:

 e.g: femtocell
 f
 fe
 fem
 femt
 femto
 femtoc
 femtoce
 femtocel
 femtocell

非常感激。

如果要獲取每個元素的每個字符,可以進行簡單的數組轉換,以獲得所有項中所有字符的數組:

var allOfThem = arr.join('').split('');

那就是:您首先將所有元素連接成一個字符串。 然后將此字符串拆分為字符數組。 然后你可以循環它。

你能提供一個你到目前為止嘗試過的例子嗎? 這樣做有助於我們回答您的任何困惑。

首先,讓我們演示如何遍歷數組中的每個元素。 我們可以按照你演示的方式聲明一個數組:

var myArray = ["elements", "are", "pretty", "cool! "];

要循環遍歷此數組,我們可以簡單地使用for循環。

for (var i = 0; i < myArray.length; ++i) {
    console.log(myArray[i]);    // this provides the element at the ith index of the array
}

這將按順序記錄:

elements
are
pretty
cool! 

您可以使用與訪問數組的各個元素完全相同的方式訪問字符串的各個字符。 試試看,看看你是否能夠到達你需要的地方。

您可以使用兩個嵌套循環,一個用於數組,一個用於字母的atrings以及String#slice

 var possibleRaysPasswords =['mobleyAndTrentonAreDead','tyrellIsElliot','dreadPirateRoberts'], i, j; for (i = 0; i < possibleRaysPasswords.length; i++) { for (j = 1; j <= possibleRaysPasswords[i].length; j++) { console.log(possibleRaysPasswords[i].slice(0, j)); } } 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

如果有什么不清楚,請告訴我。 代碼中的注釋應該告訴你發生了什么:

// making this a constant, because we only want to read from this data
const passwords = ['mobleyAndTrentonAreDead', 'tyrellIsElliot', 'dreadPirateRoberts'];

// somewhat recently, we can also define functions like this
const printPassword = password => {
  // this function prints out the password starting from the first character, all the way to its end
  // if the password is 'test', the output should be 't te tes test'

  let resultString = ''; // this will be returned later
  // let's use the good old for loop
  // start at the first character (zero-indexed), and use the counter variable i to mark the end of the substring
  for (let i=1; i <= password.length; i++) {
    resultString += password.substring(0, i) + ' ';
  }
  return resultString;
};

// iterating over every password in the passwords array,
// and log the returned string to the console
passwords.forEach(password => console.log(printPassword(password)));

user'forEach'將數組元素和'substr'迭代到字符串的一部分:

var possibleRaysPasswords =['mobleyAndTrentonAreDead','tyrellIsElliot','dreadPirateRoberts'];
possibleRaysPasswords.forEach(function(element){
   for(var i=0 ; i<element.length ; i++){
       console.log(element.substr(0,i));
   }
});

'for of'也可以用於迭代:

for (element of possibleRaysPasswords){
   for(var i=0 ; i<element.length ; i++){
       console.log(element.substr(0,i));
   }
}

就如此容易:

var letters = [];
for(let i of possibleRaysPasswords ){letters.push.apply(letters,i.split(""))}
console.log(letters);

這將創建和所有字母數組。 不知道這是不是問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM