简体   繁体   English

如何在JavaScript上的匿名函数中加入数组?

[英]How to join an array within a anonymous function on JavaScript?

Suppose I have a XML looks like: 假设我有一个XML看起来像:

<?xml version="1.0" encoding="utf-8"?>
<Lists total="1">
  <Listing>
    <Rooms>Living Room</Rooms>
    <Rooms>Dining Room</Rooms>
    <Rooms>Maid Room</Rooms>
    <Facilities>Parking></Facilities>
  </Listing>
</Lists>

I wrote a JS code to: 我写了一个JS代码来:

1) Check if the field Rooms is an array 1)检查“ Rooms ”字段是否为数组
2) Yes -> join the array by adding , and return it 2)是- >通过将加入的阵列,并返回它
3) No -> just return the string 3)否->仅返回字符串

var rooms = $(xml).find('Rooms').length > 0 ? $(xml).find('Rooms').text() : function (e) {
        $(xml).find('Rooms').each(function () {
            e += $(this).text() + ','
        })
        return e;
    }

This code doesn't return Living Room,Dining Room,Maid Room for the above XML, anyone know what wrong with my JS code? 该代码不会返回上述XML的Living Room,Dining Room,Maid Room ,有人知道我的JS代码有什么问题吗?

Thanks 谢谢

Your code can be made much simple: 您的代码可以变得非常简单:

var rooms = [];
$(xml).find('Rooms').each(function() {
    rooms.push($(this).text());
});
rooms = rooms.join(',');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM