关于js如何提取json中数组赋值给js数组以及遍历

关于js如何提取json中数组赋值给js数组以及遍历,第1张

var json={"a":"aaa","b":{"c":"ccc","d":[{"e":"01","g":"kkkk"},{"e":"07","g":"lllll"},{"e":"05","g":"xxxxx"},{"e":"03","g":"kkkk"}]}};
var arr=[];
for(var i=0;i<jsonbdlength;i++){
    arr[i]=jsonbd[i]e+"-"+jsonbd[i]g;
}
consolelog(arr);

具体代码如下所示:

1、<script>   //----------------for用来遍历数组对象

2、 var i,myArr = [1,2,3];   for (var i = 0; i < myArrlength; i++) {    consolelog(i+":"+myArr[i]);   };

3、 //---------for-in 用来遍历非数组对象   var man ={hands:2,legs:2,heads:1};   //为所有的对象添加clone方法,即给内置原型(object,Array,function)增加原型属性,该方法很强大,也很危险   if(typeof Objectprototypeclone ==="undefined"){    Objectprototypeclone = function(){};    } ;

4、  //   for(var i in man){    if (manhasOwnProperty(i)) { //filter,只输出man的私有属性     consolelog(i,":",man[i]);    };   }  ;

5、//输出结果为print hands:2,legs:2,heads:1   for(var i in man) {//不使用过滤    consolelog(i,":",man[i]);   }   ;

6、 //输出结果为://hands : 2 indexhtml:20   //legs : 2 indexhtml:20   //heads : 1 indexhtml:20   //clone : function ;

7、for(var i in man) {    if(ObjectprototypehasOwnPropertycall(man,i)) { //过滤     consolelog(i,":",man[i]);    }   };

8、 //输出结果为print hands:2,legs:2,heads:1 </script>    。

javaScript遍历对象总结:

1、

2、

//实现一个 Array each方法 实现遍历多维数组

var arr = [1,2,3,[4,[5,6]]]; //arrlength

Arrayprototypeeach = function(fn){

try{

//1 目的  遍历数组的每一项  //计数器 记录当前遍历的元素位置

thisi || (thisi=0);

//2 严谨的判断什么时候去走each核心方法

//当数组的长度大于 0 的时候 && 传递的参数 必须为函数

if( thislength>0  && fnconstructor == Function ){

// 循环遍历数组的每一项 

while( thisi < thislength ){

//获取数组的每一个值

var e = this[thisi]; //数组的每一项

//如果当前元素获取到了 并且当前元素是一个数组

if(e && econstructor == Array ){

//直接递归 *** 作

eeach(fn);

}else{

//如果不是数组 (那就是一个单个元素)

//var obj = true;

//fnapply(obj,[e]);

//这的目的就是为了把数组的当前元素 传递给fn函数,并且让函数执行

fncall(e,e);

}

thisi++

}

thisi == null ; //释放内存 垃圾回收机制回收变量

}

}catch(err){

//do something

}

return this;

}

arreach(function(item){

consolelog(item)

});

主要有三种方式,forin 、Objectkeys(obj)、ObjectgetOwnPropertyNames(obj):

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>遍历对象的几种方式</title>
</head>
<body>
</body>
<script>
const obj = {
a:1,
b:true,
c:"hello"
}
//方式1:for in方式  
for(let key  in obj){
        consolelog(key)
   }
//Objectkeys 方式 直接返回一个数组
consolelog(Objectkeys(obj))
consolelog(ObjectgetOwnPropertyNames(obj))

</script>

</html>

如果想要了解他们具体的区别的话,可以看下这篇博客JS中三种主要的遍历对象的方法:for in、Object


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/yw/13367561.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2025-08-31
下一篇2025-08-31

发表评论

登录后才能评论

评论列表(0条)

    保存