我有以下XML文档
var xml = '<t0><t1><t20>6267</t20></t1><t1><t20>556</t20></t1></t0>';
如何计算差值(6267-556)并推送数组
var myarray = [];
var xml = '<t0><t1><t20>6267</t20></t1><t1><t20>556</t20></t1></t0>';
xmlDoc = $.parseXML(xml),
$xml = $(xmlDoc),
$(xml).find('t1').each(function () {
var difference = $(this).find('t20').text();
});
答案 0 :(得分:2)
var myarray = [];
var xml = '<t0><t1><t20>6267</t20></t1><t1><t20>556</t20></t1></t0>';
$xml = $($.parseXML(xml));
var a = $(xml).find('t20').eq(0).text();
var b = $(xml).find('t20').eq(1).text();
myarray.push(a-b);
console.log(myarray);
答案 1 :(得分:2)
有很多方法可以做到这一点,这里有一个(它将从第一个中减去所有其他t20
值,因此您不仅限于两个数字):
var myarray = [];
var xml = '<t0><t1><t20>6267</t20></t1><t1><t20>556</t20></t1></t0>';
var difference = false;
$(xml).find('t1').each(function () {
if (difference === false) { // compare by type in case first num is 0
difference = $(this).find('t20').text(); // assign the first number
} else {
difference -= $(this).find('t20').text(); // subtract the others
}
});
myarray.push(difference);
alert('The difference is: ' + difference);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
答案 2 :(得分:1)
如前所述,有很多方法,所以另一种方式。 FIDDLE
var myarray = [];
var xml = '<t0><t1><t20>6267</t20></t1><t1><t20>556</t20></t1></t0>';
var difference = null;
xmlDoc = $.parseXML(xml),
$xml = $(xmlDoc),
$(xml).find('t1').each(function () {
var to_subtract = parseInt($(this).find('t20').text());
difference = (difference == null ? to_subtract : difference - to_subtract);
});
console.log(difference);
console.log(Math.abs(difference));