js遍历数组和遍历对象的区别
1个回答
展开全部
<script>
//----------------for用遍历数组象--
var i,myArr = [1,2,3];
for (var i = 0; i < myArr.length; i++) {
console.log(i+":"+myArr[i]);
};
//---------for-in 用遍历非数组象
var man ={hands:2,legs:2,heads:1};
//所象添加clone即给内置原型(object,Array,function)增加原型属性,该强危险
if(typeof Object.prototype.clone ==="undefined"){
Object.prototype.clone = function(){};
}
//
for(var i in man){
if (man.hasOwnProperty(i)) { //filter,输man私属性
console.log(i,":",man[i]);
};
}
//输结print hands:2,legs:2,heads:1
for(var i in man) {//使用滤
console.log(i,":",man[i]);
}
//输结
//hands : 2 index.html:20
//legs : 2 index.html:20
//heads : 1 index.html:20
//clone : function (){}
for(var i in man) {
if(Object.prototype.hasOwnProperty.call(man,i)) { //滤
console.log(i,":",man[i]);
}
} //输结print hands:2,legs:2,heads:1 </script>
前端工作我需要遍历些未知类型象代码:
//js遍历象
function TraversalObject(obj)
{
for (var a in obj)
{
if (typeof (obj[a]) == "object") {
TraversalObject(obj[a]); //递归遍历
}
else {
alert(a + "=" + obj[a]);//值显示
}
}
}
//遍历象所Ur值
function TraversalObject(obj)
{
for (var a in obj)
{
if(a=="Url") alert(obj[a]);/ /显示URL值
if (typeof
(obj[a]) == "object") {
TraversalObject(obj[a]);
//递归遍历
}
}
}
//----------------for用遍历数组象--
var i,myArr = [1,2,3];
for (var i = 0; i < myArr.length; i++) {
console.log(i+":"+myArr[i]);
};
//---------for-in 用遍历非数组象
var man ={hands:2,legs:2,heads:1};
//所象添加clone即给内置原型(object,Array,function)增加原型属性,该强危险
if(typeof Object.prototype.clone ==="undefined"){
Object.prototype.clone = function(){};
}
//
for(var i in man){
if (man.hasOwnProperty(i)) { //filter,输man私属性
console.log(i,":",man[i]);
};
}
//输结print hands:2,legs:2,heads:1
for(var i in man) {//使用滤
console.log(i,":",man[i]);
}
//输结
//hands : 2 index.html:20
//legs : 2 index.html:20
//heads : 1 index.html:20
//clone : function (){}
for(var i in man) {
if(Object.prototype.hasOwnProperty.call(man,i)) { //滤
console.log(i,":",man[i]);
}
} //输结print hands:2,legs:2,heads:1 </script>
前端工作我需要遍历些未知类型象代码:
//js遍历象
function TraversalObject(obj)
{
for (var a in obj)
{
if (typeof (obj[a]) == "object") {
TraversalObject(obj[a]); //递归遍历
}
else {
alert(a + "=" + obj[a]);//值显示
}
}
}
//遍历象所Ur值
function TraversalObject(obj)
{
for (var a in obj)
{
if(a=="Url") alert(obj[a]);/ /显示URL值
if (typeof
(obj[a]) == "object") {
TraversalObject(obj[a]);
//递归遍历
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询