反转数组中值的输出

时间:2017-01-03 10:26:19

标签: jquery

<div id="test"><h2>test</h2></div>

var obj = [
 {num:"1", txt:"text of 1"},
 {num:"2", txt:"text of 2"},
 {num:"3", txt:"text of 3"},
 {num:"4", txt:"text of 4"},
 {num:"5", txt:"text of 5"},
];
$.each(obj, function (i, value) {
  $('#test h2').after(obj[i].txt + "<br>");
});

输出总是颠倒过来:

text of 5
text of 4
text of 3
text of 2
text of 1

我试图这样做,但它不起作用 - 结果是一样的:

$($(obj).get().reverse()).each(function (i, value) {
  $('#test h2').after(obj[i].txt + "<br>");
});

我想要的是按照逻辑顺序输出,从1到5而不是从5到1,我怎么能实现这个呢?

3 个答案:

答案 0 :(得分:0)

由于.after()在指定元素之后插入元素,即h2,因此您将获得结果。

你非常接近,只需要reverse() obj对象

$.each(obj.reverse(), function(i, value) {
    $('#test h2').after(obj[i].txt + "<br>");
});

var obj = [{
  num: "1",
  txt: "text of 1"
}, {
  num: "2",
  txt: "text of 2"
}, {
  num: "3",
  txt: "text of 3"
}, {
  num: "4",
  txt: "text of 4"
}, {
  num: "5",
  txt: "text of 5"
}, ];
$.each(obj.reverse(), function(i, value) {
  $('#test h2').after(obj[i].txt + "<br>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
  <h2>test</h2>
</div>

您可以将.append()元素用于父test div。

$('#test').append(obj[i].txt + "<br>");

var obj = [{
  num: "1",
  txt: "text of 1"
}, {
  num: "2",
  txt: "text of 2"
}, {
  num: "3",
  txt: "text of 3"
}, {
  num: "4",
  txt: "text of 4"
}, {
  num: "5",
  txt: "text of 5"
}, ];
$.each(obj, function(i, value) {
  $('#test').append(obj[i].txt + "<br>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
  <h2>test</h2>
</div>

答案 1 :(得分:0)

由于您使用的是after,因此每当您在h2之后立即附加值时。所以请改用append。

var obj = [
 {num:"1", txt:"text of 1"},
 {num:"2", txt:"text of 2"},
 {num:"3", txt:"text of 3"},
 {num:"4", txt:"text of 4"},
 {num:"5", txt:"text of 5"},
];
$.each(obj, function (i, value) {
  $('#test').append(obj[i].txt + "<br>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"><h2>test</h2></div>

答案 2 :(得分:0)

它真的帮助你

$($(obj).get().sort()).each(function (i, value) {
  $('#test h2').after(obj[i].txt + "<br>");
});