Using array data coding structures (a)
Using an array of
js in the array
First, property
1.length set or returns the number of array elements.
2.constructor return a reference to the constructor
var a=["a","b",1,2];
alert(a.constructor)
//function Array(){
[native code]
}
Second, the definition of an array traversal
Using new Array () define an array of
//第一种,声明以后再赋值.数组可以存储任何类型的值。
var arr = new Array(); //定义一个数组arr,初始长度为0
arr[0] = 123
arr[1] = "abc";
arr[5] = false;
alert(arr[3]);//undefined,没有初始化
alert(arr);//123,abc,,,,false
alert(arr[10]);//undefined,
//如果指定了长度,但是没有赋值,他的值就会自动赋值为undefined;
//不会出现越界异常相当于定义了一个变量arr[10],没有赋值
//第二种
var arr2 = new Array(2);//规定了数组的长度为2
arr2[0] = "ddd";
arr2[1] = "www";
alert(arr2);//ddd,www
arr2[2] = "fff";//可以再次添加元素,定义的数组大小对此没有影响
alert(arr2);//ddd,www,fff
//第三种,直接赋值,
var arr3 = new Array(true,123,false);
alert(arr3);//true,123,false
js in {}, [] and the object to define an array
1. braces {}, the definition of an object represents, in most cases have pairs of attributes and values, or function.
2. [] brackets, represents an array, it can also be understood as an array object.
{3} and [] with the use, as we said, is an object {}, [] is an array, we can form an array of objects
Calling up properties of an object with a. (Dot) is superimposed, with the array [index] to access.
var LangShen = { "Name":"Lansheng",
"MyAge":[ "Age","26" ],
"MyWife":[{"Name":"Lansheng1"},{"Name":"Lansheng2"},{"Name":"Lansheng3"}]
}
Using [] array defined in a manner
var arr3 = [] ; //定义了一个数组,里面是空的
arr3.push(a);//push() 方法可向数组的末尾添加一个或多个元素,并返回新的长度。
arr3.push(b);
arr3.push(c);
arr3.push(d);
arr3.push(e);
arr3.push(h);
var arr4 = [false,"aaa",123]; //定义了一个数组,同时初始化数据
alert(arr4);//false,aaa,123
var idArr = [];
for(i=0,len=codeName.length; i<len; i++){
if(""!=codeName[i]["code"]&&""!=codeName[i]["name"])
{
var obj = {};
obj.code = codeName[i]["code"];
obj.name = codeName[i]["name"];
idArr.push(obj);
}
}
return idArr;
Defining the length of the array
alert(arr4.length) ;
//arr4.length = 100 ; //将数组的长度变为100
//alert(arr4.length) ;
//arr4[100] = 100 ; //将数组的长度变为101
//alert(arr4.length) ;
arr4.length = 2 ; //将数组的长度变为2,多余的数据将消失了
//alert(arr4[2]) ; //弹不出原来的数据了,弹出来undefined
Data defined by the definition of array subscript
var result = {};
var url = CONTEXT_PATH + '/cusviews/scada/getScadaAirData';
var retData = $.getData(url,null);
if(1000 != retData.status){
return;
}
var data = retData.data;
if(null == data || undefined == data){
return;
}
function getGasList(tagCode){
if($.isEmptyArray(data[tagCode])){
return;
}
var gasList = new Array();
for(var i=0;i<data[tagCode].length;i++){
var obj = new Object();
obj.name = data[tagCode][i].timestamp;
var arr = new Array();
arr.push(data[tagCode][i].timestamp)
arr.push(data[tagCode][i].tagValue);
obj.value = arr;
gasList.push(obj);
}
return gasList;
}
result["xijiaoList"] = getGasList("FRQA001A.PV");
result["ciquList"] = getGasList("FRQB003A.PV");
Class Array
Array of class definition, it should have substantially the same feature array, to know, as a form below the object is a class object array
What are the characteristics of it?
- By calling the subscripts, such as
array[0]
- Having a length attribute
length
- And for loop can
forEach
be traversed methods
var arrayLike = {
0: 'item1',
1: 'item2',
2: 'item3',
length: 3
}
Array class arrayLike
can be called by the subscript having a length
property, but also can be traversed by a for loop
Node obtain dom way we often use is the return of a class array, use in a method in arguments
which a keyword to get all of the parameters is also an array of class
But the array of classes but can not forEach
be traversed as forEach
a method on an array prototype chain, after all, not an array of array data, can not be used
(function (window, $, undefined) {
// 定义 通用工具方法 扩展对象基元
coreUtil = function () { return Object.apply(this, arguments); },
// 定义 jQuery 扩展对象基元
coreJquery = function () { return $.apply(this, arguments); },
coreUtil.fn = coreUtil.prototype = {};
coreJquery.fn = coreJquery.prototype = {};
coreJquery.util = coreUtil;
// 检测一个对象是否为一个数组对象或者类似于数组对(具有数组的访问方式:具有 length 属性、且具有属性名为数字的索引访问器)
// 注意:此方法传入 字符串 时执行,也会返回 true,因为 字符串 是一个字符数组。
coreUtil.likeArray = function (obj) {
if (obj == null || obj == undefined || coreUtil.isWindow(obj)) {
return false;
}
if (obj.nodeType === 1 && obj.length) {
return true;
}
var type = coreUtil.type(obj);
return type === "array" || type !== "function" && coreUtil.isNumeric(obj.length) && obj.length >= 0;
};
// 检测一个对象是否为一个数组对象或者类似于数组对(具有数组的访问方式:具有 length 属性、且具有属性名为数字的索引访问器)且不是字符串
coreUtil.likeArrayNotString = function (obj) {
return coreUtil.likeArray(obj) && !coreUtil.isString(obj);
};
})(window, jQuery);
Iterate
Ordinary for loop
var sbInfos = [ [ 12, 'A站' ], [ 11, 'B站' ], [ 3, 'C站' ], [ 14, 'D站' ],[ 13, 'E站' ], [ 25, 'F站' ] ];
var points = {};
for (var i = 0; i < sbInfos.length; i++) {
var obj = sbInfos[i];
var Item = '<li class="child"><span><input onchange="show(this);" class="Item" type="checkbox" value="'
+ obj[0] + '" /></span><a>' + obj[1] + '</a></li>';
$("#bd").append(Item);
}
var param = $(Items).val()
var ps = new Array();
ps.push(int);
points[param] = ps;
$(".jy").find("tr").each(function () {
var list = $(this).children('td:eq(1) input');
for(var i = 0;i<list.length;i++){
if(list[i].checked){
var listxz = $(list[i]).val();
if(listxz==null){
alert("有未选项,请确认");
return false;
}
}
}
Optimized version for circulation, the use of temporary variables, the length cached, to avoid duplication get the array length, when the array is large optimize the effect will be more obvious.
for(j = 0,len=arr.length; j < len; j++) {
}
for in
var ren ={};
ren.name="张三";
ren.sex="男";
ren.eat=function () {
alert("吃饭");
}
for (var i in ren) {
alert(ren[i])
}
var item = list.data[0].data;
var names = [ "JQX:抢修", "XL:泄露", "HZ:火灾", "HS:洪水","DZ:地震", "NSL:泥石流" ];
var rlt = {
"keys" : [],
"data" : []
};
for ( var o in item) { //js for
for (var i = 0, len = names.length; i < len; i++) {
var nItem = names[i], noKey = nItem.split(":")[0], nVal = nItem.split(":")[1];
if (o == noKey) {
rlt.keys.push(nVal);
var obj = {};
obj.value = item[o], obj.name = nVal;
rlt.data.push(obj);
}
}
}
forEach method callback function has three parameters: The first parameter is the content of array traversal, the second parameter is an array corresponding to the index, the third parameter is the array itself
var arr = [1,2,3,4];
arr.forEach(function(value,index,array){
array[index] == value; //结果为true
sum+=value;
});
console.log(sum); //结果为 10
The method is equivalent to:
$.each([],function(index,value,array){
//code something
})
map that is "mapped" forEach similar meaning and usage, the actual efficiency is less than the foreach. Usage namely:
arr.map(function(value,index,array){
//code
})
while iterate
var a=0
while (a<arr.length) {
alert(arr[a]);
a++
}
$ .Each to iterate
each method traverse process data, can be an array, DOM, json etc.
$(selector).each(function(index,element))
- index - the position index selector
- Element - The current element (can also use "this" selector)
Js traverse an array typically used for in each way or format selection background data according to the returned package, java traverse the array typically used for in
Two parameters, the first parameter represents a traverse the array index, the second parameter value corresponding to the index
var arr1=['aa','bb','cc','dd'];
$.each(arr1,function(i,val){
console.log(i+'```````'+val);
}
$("input:hidden").each(function(i,val){ //第一个参数表示索引下标,第二个参数表示当前索引元素
alert(i);
alert(val.name);
alert(val.value);
});
this selector to obtain the current element
$('td[aria="View_CHECK_NAME"]').each(function(){
if($(this).html()=="yes"){
$(this).attr("style","color:red; text-align:center;cursor:pointer");
}
})
The output of each li element of the text:
$("button").click(function(){
$("li").each(function(){
alert($(this).text())
});
});
Gets the element by index index
$("#ty").click(function(){
debugger;
var cancelId = "";
var Name=""
$("#RecList").next().find("[type='checkbox']").each(function(index,item){
var cancelTd = $("#RecList").next().find("tr").eq(index).find("td");
cancelId += (cancelTd.eq(1).text()+",");
Name+= (cancelTd.eq(2).text()+",");
});
cancelId = cancelId.substring(1,cancelId.length-1);
cancelId = cancelId.substring(0,cancelId.length-1);
if(cancelId == ""){
layer.msg("");
return false;
}
$.ajax({
type : "post",
url : CONTEXT_PATH + '/update',
data : {"cancelId " : cancelId,"Name":Name},
success : function(data){
if(data > 0){
$("button[name='comQue']").each(function(index,item){
$(this).trigger("click");
})
})
Two-dimensional array traversal
Two parameters, the first parameter represents a standard, a second parameter for each array of one-dimensional array
var arr2=[['aaa','bbb'],['ccc','ddd'],['eee','fff']];
$.each(arr2,function(i,item){
console.log(i+'````'+item);
}
$(function () {
$.each([["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]], function (i, el) {
console.log(i+ ":" + el);
//输出0:a,b,c 1:d,e,f 2:g,h,i 这时的i为数组下标,el相当于取这二维数组中的每一个数组
$.each(el, function (index, itemobj) {
console.log(index + ":" + itemobj);
});
});
//输出0.:a,b,c 0:a 1:b 2:c 1:d,e,f 0:d 1:e 2:f 2:g,h,i 0:g 1:h 2:i
});
Json traversal
var json1={key1:'a',key2:'b',key3:'c'};
$.each(json1,function(key,value){ //遍历键值对
console.log(key+'````'+value);
})
$(function () {
var json = [{ name: "小明", sex: "男" }, { name: "小糖", sex: "女" }, { name: "小孩", sex: "男"}]; //自定义一个json数组
$.each(json, function (index, obj) {
console.log(index + ":" + obj.name+":"+obj.sex);
});
});
Output: 0: Xiao Ming: Male 1: Little Sugar: 2 females: Children: Male
There are two-dimensional array of json objects
var arr3=[{name:'n1',age:18},{name:'n2',age:20},{name:'n3',age:22}];
$.each(arr3,function(i,val){
console.log(i+'`````'+val);
//输出
/* 0`````[object Object] 1`````[object Object] i2`````[object Object]*/
console.log(val.name); //获取每一个json里面的name值
console.log(val["name"]);
$.each(val,function(key,val2){
console.log(key+'```'+val2);
})
});
Definition and traverse the two-dimensional array of two-dimensional array
int arr[][]=new int[][]{{1,2,3},{4,5,6},{7,8,9}};
int [][]arr=new int[3][3];
arr[1][2]=3;
for(int i=0;i<arr.length;i++){
for(int j=0;j<arr[i].length;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
private String[][] homePageBlock = {
{"top_right","TOPRIGHT","TOPRIGHTNAME"},{"middle_left","MIDDLELEFT","MIDDLELEFTNAME"},
{"middle_center1","MIDDLECENTER1","MIDDLECENTER1NAME"},{"middle_center2","MIDDLECENTER2","MIDDLECENTER2NAME"},
{"middle_center3","MIDDLECENTER3","MIDDLECENTER3NAME"},
{"middle_roll","MIDDLEROLL","MIDDLEROLLNAME"},{"bottom_right","BOTTOMRIGHT","BOTTOMRIGHTNAME"}
};
for (int i = 0; i < homePageBlock.length; i++) {
if("TOPRIGHT".equals(homePageBlock[i][1]))
{
model.addAttribute(homePageBlock[i][1], dataList.size() <= 3 ? dataList : dataList.subList(0, 3));
}
else
{
model.addAttribute(homePageBlock[i][1], dataList.size() <= 7 ? dataList : dataList.subList(0, 7));
}
}
jquery array of integrated use
var _cache = function () {
var cache = {};
this.set = function(dicobj) {
if ($.util.isObject(dicobj)) {
if (dicobj !== undefined && dicobj.data !== undefined)
$.each(dicobj.data,
function(i, n) {
var tempitem = cache[i] = cache[i] || {};
tempitem.originalData = n;
$.each(n,
function(j, k) {
//console.log(k);
//k[k.id] = k.text;
if (k.id !== undefined && k.id !== "" && k.text !== undefined)
tempitem[k.id] = k.text;
if (k.children) {
recursiondic(tempitem, k.children);
}
});
});
} else {
throw "字典初始化仅支持对象信息";
}
};
/**
* 递归子节点
* @param {any} obj
* @param {any} children
*/
function recursiondic(obj, children) {
$.each(children,
function (j, k) {
//console.log(k);
if (k.id !== undefined && k.id !== "" && k.text !== undefined)
obj[k.id] = k.text;
if (k.children) {
recursiondic(obj, k.children);
}
});
}
/**
* 获取字典数据 x.originalData 是原始数据结构
* @param {any} dicCode
*/
this.get = function(dicCode) {
debugger;
return $.extend({}, cache[dicCode]);
};
/**
* @param {string} diccodes
* @param {function} func
*/
this.initDictionary = function (diccodes, func) {
$.get("system/dic/getDicByCodes/" + diccodes,
function (data) {
$Core.DicCache.set(data);
if (func !== undefined)
func(data);
});
};
}
$Core.DicCache = new _cache();
js array method
array object's method:
1. the Join (): Each data separated by commas default
2. push (): add an element to the end of the array
3. reverse (): reverse order
4. shift (): Delete and returns the first element
5. sort (): sort
by default first number can be converted to a string type and number of types of discharge them together (Comparative Switch string type)
conversion is not compared as a group
if you want were compared according to their own rules, then you need to pass a function of the type of parameters for a more rules.
A. delete or add classes
1. myarr.push (array elements ......) using the push () method can be added to one or more array entry end of the array, the return value is the length of the new array. You can add multiple elements once
var radioKeys = [];
$.each(data.data.deviceUserList, function (k, j) {
var maps = {};
maps.radioIds = j.checkItemId;
maps.radioValues = j.checkIsRight;
radioKeys.push(maps);
}
$.each(radioKeys, function (k, j) {
$($('input[name="'+j.radioIds+'"]')[j.radioValues-1]).attr("checked",true);
});
2. unshift () method can add one or more arrays in front of the array of items:
var deviceUserList = [];
$.each(data.data.deviceUserList,function(k,j){
deviceUserList.unshift(j);
})
3. myarr.pop () to delete the last element of an array and returns the removed element
var a=["a","b",1,2];
alert(a.pop())
4. myarr.shift () Removes the first element of the array, return the removed element
var a=["a","b",1,2];
alert(a.shift())
var arr = [3,8,"23","34",123,"abc","ab"] ;
alert(arr.shift())
The universal Remove Add function
myarr.splice (index, the number of added elements .....) index starts from where to add or remove, must be a numeric type (array indices), a predetermined number of the deleted number, 0 if it is not deleted, you need to add elements, the elements can be used as replacement
If there are elements that were removed, return the removed elements
var a=["a","b",1,2];
alert(a.splice(1,0,"c","d"))
B. Conversion array
mystr.split () method of the string to the array
var s = "abc,abcd,aaa";
var ss = s.split(",");// 在每个逗号(,)处进行分解。
myarr.join ([delimiter]) array into a string
var a, b;
a = new Array(0,1,2,3,4);
b = a.join(",");
The array element according to the specified composition into a string delimiter, the delimiter if not specified, the default is to use ","
return result is combined into a string
var a=["a","b",1,2];
alert(a.join()) //默认用逗号连接
alert(a.join("-"))
arr2.join(".")
alert(arr.join("")) ; //用空字符串连接
var content= [];
content.push("<div class='input-card content-window-card'>");
content.push("<div style=\"padding:7px 0px 0px 0px;\">");
content.push("<p class='input-item'>地址:"+ data[i].address +"</p>");
content.push("<p class='input-item'>事件来源:"+ data[i].address +"</p>");
content.push("<p class='input-item'>事件原因:"+ data[i].address +"</p>");
</div>");
drawPoint.type["infowindow"]={
content:content.join(""),
xoffset: 0,
yoffset:-31,
width:360,
height:100
};
Dividing the array myarr.slice C. () taken from the specified start position to the end position (not included) of the element. If you do not specify an end position, from the start position designated to take to the end (array index) support (beginning -1) number Returns a new array.
var a=["a","b",1,2,"百度","www.baidu.com"];
alert(a.slice(2,4))
alert(a.slice(2))
alert(a.slice(-2,-1))
Sort D.
var arr = [3,8,"23","34",123,"abc","ab"] ;
arr.reverse() ;//颠倒数组元素
alert(arr1.sort()) ;
alert(arr1.sort(function(a,b){ //传递一个function类型参数,制定我们的比较规则
if(a *1 > b*1)
return 1 ;
else
return -1 ;
})) ;
Bubble sort
myarr.sort () to sort the array, without parameters, the ordered alphabetically coding, if you want to sort according to other sequences, to provide a function.
var arr=[2,1,34,12,45]
// 2 1 1 1 1
// 1 2 2 2 2
// 34 34 34 12 12
// 12 12 12 34 34
// 45 45 45 45 45
function mySort (fun) {
for (var i=0; i<this.length; i++) {
for (var j=0; j<this.length-i; j++) {
if(this[j]>this[j+1]){
var aa=this[j];
this[j]=this[j+1]
this[j+1]=aa;
}
}
}
return this
}
Array.prototype.mySort= mySort
alert(arr.mySort())
sort provides two sorting parameters (A, b)
A <b A b before the
A b =
A <b
sort()
var a=["b","a","c","www.baidu.com"];
ar a=[1,3,5,2];
var a=[12,34,123]
a.sort(function(a,b) {
return a-b
});
alert(a)
E. connection array
myarr.concat ()
to connect two or more arrays, and returns a new array, but has no effect on the original array.
var a=[1,2,3];
var c=["a","b","c"]
alert(a.concat(a,c))
arr.concat(arr2)
Complex
<script type="text/javascript">
var arr=new Array();
var arr2=new Array(3);
arr[0]="jack";
arr[1]="marry";
arr[2]="tom";
arr[3]="lucy";
arr[4]="june";
arr2[0]=2;
arr2[1]=1;
arr2[2]=5;
for(var i=0;i<arr.length;i++){
document.write(arr[i]+"<br/>");
}
document.write("<hr/>");
var o;
for(o in arr2){
document.write(o+" "+arr2[o]+"<br/>");
}
document.write("<hr/>");
document.write("sort()"+arr.sort()+"<br/>");
document.write("sort()"+arr2.sort()+"<br/>");
document.write("<hr/>");
document.write("join()"+arr.join()+"<br/>");
document.write("join()"+arr2.join(".")+"<br/>");
document.write("<hr/>");
document.write("concat()"+arr.concat(arr2)+"<br/>");
document.write("<hr/>");
document.write("reverse()"+arr.reverse()+"<br/>");
</script>
js interpretation array contains an element
Method using jquery comes inArray
var initParam=$("input[name='ids']").val().split(',')||[];
var codeName=new Array();
for(var i=0;i<initParam.length;i++){
var param = new Object();
param.code = initParam[i];
param.name = paramName.split(',')[i];
codeName.push(param);
}
if($.inArray(data[k].userId,initParam)=="-1"){
initParam.push(data[k].userId);
var names={};
names.name=data[k].name;
names.code=data[k].userId;
codeName.push(names);
}
var idArr = [];
for(i=0,len=codeName.length; i<len; i++){
if(""!=codeName[i]["code"]&&""!=codeName[i]["name"])
{
var obj = {};
obj.code = codeName[i]["code"];
obj.name = codeName[i]["name"];
idArr.push(obj);
}
}
return idArr;
Custom method to achieve
var names = ["00:00","23:00","22:00","21:00","20:00","19:00","18:00","17:00","16:00","15:00","14:00","13:00","12:00","11:00","10:00","09:00","08:00","07:00","06:00","05:00","04:00","03:00","02:00","01:00"];
var url = CONTEXT_PATH +"/cusviews/dev/getRadarChartName";
var param = {
deviceCode:deviceCode
}
var retData = $.getData(url,param)
if(1000!=retData.status){
return;
}
var data = retData.data;
if(null==data){
return;
}
var rlt = {
"data" : []
};
var rltdata = [];
var dataList = new Array();
function isInArray(arr,value){
for(var i = 0; i < arr.length; i++){
if(value === arr[i]){
return true;
}
}
return false;
}
$.each(data.textlist,function(j,k){
let obj = {};
if(isInArray(names,k.substring(11,16))){
obj.text = k.substring(11,13);
}else{
obj.text = "";
}
obj.max = data.maxlist[j];
rlt.data.push(obj);
})
1, by indexof way to see whether to include an element, the method can return a string value of the specified position of the first occurrence of the string. If the string value to be retrieved is not present, then the method returns -1.
var str = "123";
if(str.indexOf("3") != -1){//true
}
if(ids.indexOf(",") > -1)
ids = ids.substring(0, ids.length() - 1);
}
2, search () method is used substring search character string specified, retrieving or regular expression matching substring. If no matches any substring, or -1.
var str = "123";
console.log(str.search("3") != -1 ); //true
3, match () method retrieves the value specified in string, or to find one or more regular expression matching.
var str = "123";
var reg = RegExp(/3/);
if(str.match(reg)){
// 包含
}
4, test () method retrieves the value specified in the string. Returns true or false.
var str = "123";
var reg = RegExp(/3/);
console.log(reg.test(str)); // true
5, exec () method is used to retrieve the matching string expressions positive. It returns an array in which to store the matching results. If a match is not found, the return value is null.
var str = "123";
var reg = RegExp(/3/);
if(reg.exec(str)){
// 包含
}
6, js determines whether the array contains a string
var codeName=new Array();
for(var i=0;i<initParam.length;i++){
var param = new Object();
param.code = initParam[i];
param.name = paramName.split(',')[i];
codeName.push(param);
}
if(!codeName.hasOwnProperty(data[k].memberId)){
}
7, jquery determines whether the array contains a string
var initParam=$("input[name='ids']").val().split(',')||[];
if($.inArray(data[k].userId,initParam)=="-1"){
initParam.push(data[k].userId);
var names={};
names.name=data[k].name;
names.code=data[k].userId;
codeName.push(names);
}