对象的一些处理
for in 循环遍历对象自身的和继承的可枚举属性,不含Symbol属性
var numbers = [4, 9, 16, 25]
for (const key in numbers) {
console.log(key)
}
输出:0,1,2,3
Object.keys() 返回一个数组,包括对象自身的所有可枚举属性,不含Symbol属性和继承属性
let obj = {
a:'lulu',
b:'lucy',
c:'roy'
}
let value = Object.keys(obj)
打印value为 ['a', 'b', 'c']
Object.values(),与Object.keys()对应的一个方法,返回一个数组,包括对象的所有属性具体值
let obj = {
a:'lulu',
b:'lucy',
c:'roy'
}
let value2 = Object.values(obj)
打印value2为['lulu', 'lucy', 'roy']
Object.getOwnPropertyNames(),返回一个数组,包含对象自身的所有属性,包括不可枚举属性,不含Symbol属性
let obj = {
a:'lulu',
b:'lucy',
c:'roy'
}
let a = Object.getOwnPropertyNames(obj)
打印a为['a', 'b', 'c']
遍历不可枚举属性
let num = new Number()
for(let i in num){
console.log(i)
}
打印为undefined
Object.getOwnPropertyNames(num)
打印为[]
数组的一些处理
for of 不改变原数组,只能遍历有iterator接口的对象
var numbers = [4, 9, 16, 25]
for(let item of numbers){
item = item*2
}
输出numbers=[4, 9, 16, 25]
for in 改变原数组,无需要求对象须有iterator接口
var numbers = [4, 9, 16, 25]
for(let key in numbers){
numbers[key] = 2
}
输出numbers = [2, 2, 2, 2]
foreach 不改变原数组
numbers = [2, 2, 2, 2]
numbers.forEach((item,index) => {
item =3
})
输出numbers = [2, 2, 2, 2]
filter 数组过滤,不改变原数组,返回的新数组需要对象接收
numbers = [2, 2, 2, 2]
let numbers2 = numbers.filter((item)=>item !=2)
输出numbers2=[],numbers = [2, 2, 2, 2]
map 对数组的每个值做处理,不改变原数组,返回的新数组需要对象接收
numbers = [2, 2, 2, 2]
let numbers1 = numbers.map((nums)=> nums*2)
输出numbers1 =[4, 4, 4, 4],numbers = [2, 2, 2, 2]
Array.from() 对象转数组,浅拷贝
let obj = {
0 : 'hello',
1 :'world',
2 :['black','white'],
length:3
}
let obj1 = Array.from(obj)
打印obj1 = [
0: "hello"
1: "world"
2: (2) ['black', 'white']
length: 3
]
obj[2][0]='pink'
打印obj1 = [
0: "hello"
1: "world"
2: (2) ['pink', 'white']
length: 3
]
indexof 返回查找项在数组中第一次出现的位置
num = [1,2,3,1]
let a = num.indexOf(1)
打印a = 0
includes 判断数组中是否存在某一项
num = [1,2,3,1]
num.includes(3)
结果为ture
some 某一项满足条件即返回true
let num = [1,2,3,1]
num.some((item)=>{return item >2})
结果为ture
every 每一项满足条件才返回true
let num = [1,2,3,1]
num.every((item)=>{return item >2})
结果为false
实例:
深拷贝(仅做了数组和对象的分类)
operson = {
name:'royal',
age:'21',
gender:'girl',
likefruite:['apple','banana','orange']
}
nperson = {}
function deepCopy(newone, oldone) {
for (const k in oldone) {
let item = oldone[k];
if (item instanceof Array) {
newone[k] = [];
deepCopy(newone[k], item);
} else if (item instanceof Object) {
newone[k] = {};
deepCopy(newone[k], item);
} else {
newone[k] = item;
}
}
}
deepCopy(nperson,operson)
字符串处理
字符串截取
var str="Hello world!"
var n=str.substr(2,3)
*n* 输出结果:
llo
实例:过长字符串折行显示
formatter: (name) => {
if (!name) return '';
let word = '';
let num = Math.ceil(name.length / 15);
if (num > 1) {
for (let i = 1; i <= num; i++) {
word += name.substr((i - 1) * 15, 15);
if (i < num) {
word += '\n';
}
}
} else {
word += name.substr(0, length);
}
return word;
},