JS常見用法(2)-- 數(shù)組/字符串/對(duì)象操作

一、字符串

字符串常用方法:https://www.cnblogs.com/l1pe1/p/6197371.html

截取字符串(slice)

 str.slice(0, 10)  

http://www.cnblogs.com/lmsblogs/p/5876384.html

  • 刪除字符串最后一位(slice)
str.slice(0,str.length-1)

https://www.jb51.net/article/126580.htm

數(shù)組和字符串的轉(zhuǎn)換(join & split)

一、數(shù)組轉(zhuǎn)字符串
let arr = [a,b,c,d,e]
b = arr.join(''); // abcde
let arr = [a,b,c,d,e]
b = arr.join(','); // a,b,c,d,e ——數(shù)組轉(zhuǎn)字符串,用’,‘隔開
二、字符串轉(zhuǎn)數(shù)組
let arr = abcde
c = arr.split(''); // [a,b,c,d,e]

https://www.cnblogs.com/LeoBoy/p/5899734.html
https://www.cnblogs.com/guorange/p/7127839.html

獲取字符串最后一位方法(charAt)

str.charAt(str.length – 1)

https://www.cnblogs.com/LChenglong/p/6856530.html

返回某個(gè)指定的字符串值在字符串中首次出現(xiàn)的位置(indexOf)

 var str="Hello world!"
document.write(str.indexOf("Hello") + "<br />")   // 0
document.write(str.indexOf("World") + "<br />")  // -1  不存在
document.write(str.indexOf("world"))  // 6

http://www.w3school.com.cn/jsref/jsref_indexOf.asp

截取從 start 下標(biāo)開始的指定數(shù)目的字符(substr)
var str="Hello world!"George.John.Thomas
document.write(str.substr(3))  // lo world!
var str="Hello world!"
document.write(str.substr(3,7))  // lo worl

http://www.w3school.com.cn/jsref/jsref_substr.asp

為數(shù)值補(bǔ)定指定位數(shù)(padStart)
var month = 8
month = month.padStart(2, '0') // 08

https://blog.csdn.net/qq_37548296/article/details/107259899

判斷字符串為全數(shù)字

     if (!/^[0-9]+$/.test(item.vacationDate)) {
        this.$message.warning('調(diào)休天數(shù)必須是數(shù)字')
        return
      }

https://zhidao.baidu.com/question/1050724412676679539.html

判斷字符串是否包含某個(gè)字段

  • 方法1:將字符串轉(zhuǎn)化為數(shù)組 判斷是否包含
      let str = '北京,上海'
      let arr = str.split(',')
        console.log(arr)
      arr.forEach((item, index) => {
        console.log(item)
        if (item == '北京' || item == '全國(guó)') {
          console.log(111)
          // this.flag = true
        }
      }, this)
  • 方法2:indexOf 直接判斷
      let str = '北京,上海'
      console.log(str.indexOf('北京'))
      if (str.indexOf('北京') != -1 || str.indexOf('全國(guó)') != -1) {
        console.log(11)
      } else {
        console.log(22)
      }

二、數(shù)組

往數(shù)組開頭/結(jié)尾添加數(shù)據(jù)(unshift、push)

var arr = [ 1,2,3 ];
alert( arr.unshift( 'abc' ) );   // 4 返回的是長(zhǎng)度
alert( arr.push( 'abc' ) );   // 4 返回的是長(zhǎng)度
arr.unshift( 'abc' )
arr.push( 'abc' )
alert(arr)  // ['abc',1,2,3,'abc']  // 返回?cái)?shù)組

https://www.cnblogs.com/SongHuiJuan/p/6627490.html

數(shù)組倒序(reverse)

let arr = [1,2,3]
let arr2 = arr.reverse()
console.log(arr2) // [3,2,1]

https://www.cnblogs.com/tunshiyublogs/p/9363890.html

求數(shù)組最大值 (Math.max)

let max = Math.max.apply(null, arr)

合并兩個(gè)數(shù)組(concat)

let a = [1,2,3];
let b = [4,5,6];
let c = [7];
let d = a.concat(b, c);   // [1,2,3,4,5,6,7];

https://www.cnblogs.com/koala0521/p/7278056.html

判斷一個(gè)數(shù)組是否包含一個(gè)指定的值 (indexOf)

let arr = ['something', 'anything', 'nothing', 'anything'];
let index = arr.indexOf('nothing');
console.log(index) //結(jié)果是2

https://www.cnblogs.com/hepengqiang/p/9822118.html

數(shù)組刪除(splice)

一、刪除數(shù)組里的某個(gè)元素
var index = this.indexOf(val);
if (index > -1) {
this.splice(index, 1);
}
二、數(shù)組刪除指定下標(biāo)
//刪除起始下標(biāo)為1,長(zhǎng)度為2的一個(gè)值(len設(shè)置2)
var arr2 = ['a','b','c','d']
arr2.splice(1,2);
console.log(arr2); 
//['a','d']
三、delete方法刪除掉數(shù)組中的元素后,會(huì)把該下標(biāo)出的值置為undefined,數(shù)組的長(zhǎng)度不會(huì)變
var arr = ['a','b','c','d'];
delete arr[1];
arr;
//["a", undefined × 1, "c", "d"] 中間出現(xiàn)兩個(gè)逗號(hào),數(shù)組長(zhǎng)度不變,有一項(xiàng)為undefined

JS刪除數(shù)組里的某個(gè)元素方法
http://caibaojian.com/js-splice-element.html
https://www.jb51.net/article/134312.htm
JS刪除數(shù)組中指定的對(duì)象
https://blog.csdn.net/frankenstein_/article/details/82788490
js增加移除替換數(shù)組里的某個(gè)元素
https://blog.csdn.net/hedy17/article/details/79378774

數(shù)組截取 -- slice和splice的區(qū)別

一、
slice(start,end) 第二個(gè)值是結(jié)束位置(包含開始索引,不包含結(jié)束索引,索引從0開始,如果第二個(gè)值為空,則截取到數(shù)組最后)
splice(start,length) 第二個(gè)值是長(zhǎng)度
二、
slice 原數(shù)組不變

splice 原數(shù)組中的數(shù)值被剔除掉了

let y = [0,1,2,3,4,5,6,7,8,9]
console.log(y.splice(2,5)); //2,3,4,5,6
console.log(y); // [0,1,7,8,9]顯示原數(shù)組中的數(shù)值被剔除掉了

https://cncat.cn/post-285.html

es6,數(shù)組去重

this.newarr = Array.from(new Set(this.arr))

判斷一個(gè)值是不是數(shù)組

let arr = []
let obj = {}
console.log(arr instanceof Array); //true
console.log(obj instanceof Array); //false

https://www.cnblogs.com/Walker-lyl/p/5597547.html

原生js,將數(shù)組每n個(gè)存為一個(gè)數(shù)組

// JS 如何從一個(gè)length為12的數(shù)組中按順序取每5個(gè)元素為一組放到新數(shù)中,
// 最后不夠5個(gè)的也存為一個(gè)數(shù)組
var SplitArray = function(N,Q)
{
    var R = [],F;
    for (F = 0;F < Q.length;) R.push(Q.slice(F,F += N))
    return R
}
var arr = [1,2,3,4,5,6,7,8,9,10,11,12];
console.log(SplitArray(5,arr))

https://zhidao.baidu.com/question/813779575873380212.html

清空數(shù)組的三種方法

var ary = [1,2,3,4]; 
ary.splice(0,ary.length); // splice
ary.length = 0; // length賦值為0
ary = []; // 賦值為一個(gè)空數(shù)組;更快,效率更高

https://blog.csdn.net/p358278505/article/details/70193930

判斷兩個(gè)數(shù)組是否相等

當(dāng)兩個(gè)數(shù)組元素排序不相同時(shí),先排序,再比較。如果是對(duì)象數(shù)組,可以結(jié)合 JSON.stringify 來使用。

var isNotChange =
        clinic_ids.length === ids.length &&
        clinic_ids.sort().toString() === ids.sort().toString();

https://www.jb51.net/article/247032.htm

從數(shù)組中隨機(jī)取值

var items = ['1','2','4','5','6','7','8','9','10'];
var item = items[Math.floor(Math.random()*items.length)];
  • 如果想取多個(gè),可以直接循環(huán)添加到數(shù)組里,也可以直接賦值,如下:
let colorList = ['#C05155', '#5E76D7', '#F7BB60', '#89B77E']
info_data.forEach((item, index) => {
   item.color = colorList[Math.floor(Math.random()*colorList.length)]
}, this)
為span隨機(jī)設(shè)置背景顏色
<li v-for="(datas , indexs) in info_data" :key="datas.id">
    <span :style="{background:datas.color}">{{datas.user_name}}</span>
</li>

https://blog.csdn.net/web_leeleon/article/details/80308727

js去除數(shù)組中的null及空值

var arr = ['2','3','',null,undefined,'7',' ','9'];
var r = arr.filter(function (s) {
    return s && s.trim(); // 注:IE9(不包含IE9)以下的版本沒有trim()方法
});
console.log(r);

https://blog.csdn.net/qq_37796017/article/details/90229667

交換數(shù)組兩個(gè)數(shù)位置(3種方法)

arr[index1] = arr.splice(index2, 1, arr[index1])[0];
arr[index1] = [arr[index2],arr[index2]=arr[index1]][0];
[a,b] = [b,a]; 

http://www.itdecent.cn/p/10cce4cce7f8

數(shù)組轉(zhuǎn)對(duì)象 {key: value}

[{ id: 1, name: '張三' },{ id: 2, name: '李四' }] 轉(zhuǎn)化為 {1:'張三', 2:'李四'}

let arr = [{ id: 1, name: '張三' },{ id: 2, name: '李四' }]
let obj = {}
arr.forEach(item => obj[item.value] = item.name)

https://www.cnblogs.com/pine007/p/16363288.html

js數(shù)組根據(jù)多個(gè)屬性進(jìn)行排序

https://blog.csdn.net/wyg1995/article/details/79432489

js根據(jù)json數(shù)據(jù)中的某一個(gè)屬性來給數(shù)據(jù)分組

var arr = [{"Group":1,"Groupheader":"質(zhì)量管理","Leftimg":"","Left":"","Min":"","Right":"","Rightimg":""},
{"Group":1,"Groupheader":"","Leftimg":"","Left":"","Min":"質(zhì)量巡檢","Right":"","Rightimg":""},
{"Group":2,"Groupheader":"設(shè)備管理","Leftimg":"","Left":"","Min":"","Right":"","Rightimg":""}]

 var map = {}
            var dest = [];
            for(var i = 0; i < arr.length; i++){
                var ai = arr[i];
                if(!map[ai.Group]){
                    dest.push({
                        Group: ai.Group,
                
                        data: [ai]
                    });
                    map[ai.Group] = ai;
                }else{
                    for(var j = 0; j < dest.length; j++){
                        var dj = dest[j];
                        if(dj.Group == ai.Group){
                            dj.data.push(ai);
                            break;
                        }
                    }
                }
            }
            console.log(dest)

[
    {
        "Group": 1,
        "data": [
            {
                "Group": 1,
                "Groupheader": "質(zhì)量管理",
                "Leftimg": "",
                "Left": "",
                "Min": "",
                "Right": "",
                "Rightimg": ""
            },
            {
                "Group": 1,
                "Groupheader": "",
                "Leftimg": "",
                "Left": "",
                "Min": "質(zhì)量巡檢",
                "Right": "",
                "Rightimg": ""
            }
        ]
    },
    {
        "Group": 2,
        "data": [
            {
                "Group": 2,
                "Groupheader": "設(shè)備管理",
                "Leftimg": "",
                "Left": "",
                "Min": "",
                "Right": "",
                "Rightimg": ""
            }
        ]
    }

https://blog.csdn.net/firoly/article/details/54314367

三、對(duì)象

js對(duì)象屬性遍歷(for…in…)

通過for…in…循環(huán)來實(shí)現(xiàn)對(duì)對(duì)象屬性的遍歷輸出
http://baijiahao.baidu.com/s?id=1599805069461530979&wfr=spider&for=pc

  • 獲取對(duì)象key值與value值的方式
var obj = {
            'name': '楊',
            'year': 27
        }
        var key = []
        var value = []
        for (var i in obj) {
            key.push(i)
            value.push(obj[i])
        }
        console.log(key)
        console.log(value)

https://www.cnblogs.com/xpcool/p/9501323.html

刪除對(duì)象屬性 (delete)

for(var key in student){
delete student[key];
}
console.log(student);

https://www.cnblogs.com/isykw/p/6869084.html

將對(duì)象排序輸出 -- Object.keys(obj)

eg:
var anObj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.keys(anObj));   // console: ['2', '7', '100']

對(duì)象長(zhǎng)度 -- Object.keys(obj).length

1、傳入對(duì)象,返回屬性名
var obj = {'a':'123','b':'345'};
console.log(Object.keys(obj)); //['a','b']
2、傳入字符串或者數(shù)組,返回索引
var str = 'ab1234';
console.log(Object.keys(obj)); //[0,1,2,3,4,5]

  • 實(shí)例:
if (Object.keys(obj).length === 0) {
  alert('請(qǐng)選擇至少一個(gè)選項(xiàng)')
  return
}

js 判斷對(duì)象中所有屬性是否為空

for (var key in this.ruleForm) {
   if (this.ruleForm[key]) {
       this.flag = true
    }
}

https://www.cnblogs.com/crazycode2/p/8926103.html

js判斷對(duì)象是否為空對(duì)象的幾種方法

v-if=" JSON.stringify(obj) == '{}' "  // 即obj為空對(duì)象時(shí)

四、json

json.parse (從一個(gè)字符串中解析出json對(duì)象)
 var data = '{"name":"goatling"}'
console.log(JSON.parse(data))   //  {name:"goatling"}
console.log(typeof JSON.parse(data))   // object
json.stringify (從一個(gè)對(duì)象中解析出字符串)
 var data = {name:'goatling'}
console.log(JSON.stringify(data))   //  '{"name":"goatling"}'
console.log(typeof JSON.stringify(data))  // string

https://www.cnblogs.com/goatling/p/6293692.html

五、計(jì)算

除法 向上取整(Math.ceil)

1.丟棄小數(shù)部分,保留整數(shù)部分 
js:parseInt(7/2)
2.向上取整,有小數(shù)就整數(shù)部分加1 
js: Math.ceil(7/2)  // 4
3,四舍五入. 
js: Math.round(7/2)
4,向下取整 
js: Math.floor(7/2) // 3

https://blog.csdn.net/xinyuan_java/article/details/40300873

絕對(duì)值 (Math.abs)

Math.abs(7.2) // 7.2
Math.abs(-2.1)  // 2.1
Math.abs(-8.1) // 8.1

余數(shù)(%)

var box = 10%3
console.log(box) // 1

https://www.cnblogs.com/xiaoxinzi/p/8482836.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容