JavaScript數組循環遍歷

1. for in語句的用法

for...in 語句用於遍歷數組或者對象的屬性(對數組或者對象的屬性進行循環操作)類似於for()循環。

  • 語法:
          for (variable in 對象) { 
              在此執行代碼 
          }
          variable是聲明一個變量,數組的一個元素或者是對象的一個屬性在循環體內部,對象的一個屬性名會被作爲字符串賦給變量variable
  • 例子:
          var a = ["a","b","c"];
          for(var el in a){
              alert(a[el]);
          }
  • 注意:用for/in語句可以遍歷一個對象"可枚舉"的屬性,但並非一個對象的所有屬性都是可枚舉的,
        通過JavaScript代碼添加到對象的屬性是可枚舉的,而內部對象的預定義屬性(如方法)通常是不可枚舉的.
        可以通過propertyIsEnumerable屬性來判斷屬性是否可枚舉的.

2. JS/jQuery 遍歷對象屬性

1)Javascript For/In 循環: 循環遍歷對象的屬性
  • 例子:
              var person={fname:"John",lname:"Doe",age:25};
              for (x in person)  
                {  
                  txt=txt + person[x];  
                }  
              結果:JohnDoe25
2jQuery jQuery.each() 遍歷對象屬性
  • var arr = ["one", "two", "three", "four", "five"];
  • var obj = { one: 1, two: 2, three: 3, four: 4, five: 5 };
  • 例子1:(遍歷數組)
              var text = "Array ";  
              jQuery.each(arr, function(i, val) {  
                  text = text + " #Index:" + i + ":" + val;  
              });  
              console.log(text);  
              //Array  #Index:0:one #Index:1:two #Index:2:three #Index:3:four #Index:4:five
  • 例子2:(遍歷對象)
              text = "Object ";  
              jQuery.each(obj, function(i, val) {
                  text = text + "Key:" + i + ", Value:" + val;  
              });  
              console.log(text);  
              //Object Key:one, Value:1Key:two, Value:2Key:three, Value:3Key:four, Value:4Key:five, Value:5

3. js 數組,字符串,json互相轉換

(1).數組轉字符串

  • 例子:
           var arr = [1,2,3,4,'巴德','merge'];
           var str = arr.join(',');
           console.log(str); // 1,2,3,4,巴德,merge

(2).字符串轉數組

  • 例子:
          var str = '1,2,3,4,巴德,merge';
          var arr = str.split(',');
          console.log(arr);     // ["1", "2", "3", "4", "巴德", "merge"]   數組
          console.log(arr[4]);  // 巴德

(3).字符串轉數組,數組轉數組格式化,數組格式化轉數組

  • 例子:
          var str = '1,2,3,4,巴德,merge';
          var arr = str.split(',');
          var strify = JSON.stringify(arr);
          console.log(arr);       // ["1", "2", "3", "4", "巴德", "merge"]   數組
          console.log(arr[4]);    // 巴德
          console.log(strify);    // ["1", "2", "3", "4", "巴德", "merge"]   字符串
          var arrParse = JSON.parse(strify);
          console.log(arrParse);  // ["1", "2", "3", "4", "巴德", "merge"]   數組
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章