我的对象是,
var names =["LET_ABC","PET_DEF","Num_123","Num_456","SET_GHI","RET_JKL"];
现在我必须将包含“Num
”的值移到最后,这意味着在“Num
”值之后应该没有值。
这是我如何将值添加到数组
result.each(function () {
var tempObject = {},
attributes = $(this).data();
names.push(attributes.prefix+ '_' + attributes.value)
});
我可以以某种方式操纵上面的代码,使“Num
”值最后移动。
我需要类似的东西,
var names =["LET_ABC","PET_DEF","SET_GHI","RET_JKL","Num_123","Num_456"];
答案 0 :(得分:2)
for(var i=0;i<names.length;i++){
if(names[i].match("^Num")){
names.push(names.splice(i, 1)[0]);
}
}
答案 1 :(得分:1)
工作示例(评论中有解释): -
var names =["LET_ABC","LET_DEF","Num_123","Num_456","LET_GHI","LET_JKL"];//your array
function movetoLast(names,checkword){// function with array and checking prefix
$(names).each(function(index,value){ // iterate over array
if(value.indexOf(checkword) >= 0){ // check value have that prefix or not in it
names.push(names.splice(names.indexOf(value), 1)[0]); // if yes move that value to last in array
}
});
return names; // return modified array
}
var names = movetoLast(names,"Num");// call function
console.log(names); // print modified array in console
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
答案 2 :(得分:1)
尝试使用此简单的Array#filter
和Array#concat
var names = ["LET_ABC", "PET_DEF", "Num_123", "Num_456", "SET_GHI", "RET_JKL"];
console.log(names.filter(a => !a.match(/(\d+)/g)).concat(names.filter(a => a.match(/(\d+)/g))))
&#13;
答案 3 :(得分:0)
我会将数字放在一个单独的数组中,以便在最后连接两个数组。
result.each(function () {
var tempObject = {}, attributes = $(this).data();
var numsArray = [];
if (attributes.prefix==Num){
numsArray.push(attributes.prefix+ '_' + attributes.value);
}else{
names.push(attributes.prefix+ '_' + attributes.value)
}
names.concat(numsArray);
});
答案 4 :(得分:0)
如果数组具有“Num”前缀并使用 unshift 将值添加到数组的开头,请使用 push 将值添加到数组末尾如果它没有“Num”前缀。工作代码:
var names =["LET_ABC","PET_DEF","Num_123","Num_456","SET_GHI","RET_JKL"];
$(document).ready(function(){
result_array = [];
$.each(names, function(index, value){
if (value.substring(0,3)=="Num"){
result_array.push(value);
} else{
result_array.unshift(value);
};
});
console.log(result_array);
});