JS技巧记录

一、语法

Object.keys(obj)

参数:要返回其枚举自身属性的对象

返回值:一个表示给定对象的所有可枚举属性的字符串数组

let person = {name:"张三",age:25,address:"深圳",getName:function(){}}

Object.keys(person).map((key)=>{

  person[key] // 获取到属性对应的值,然后做一些处理

}) 

 

二、Object.values()和Object.keys()是相反的操作,把一个对象的值转换为数组

 

三、reverse() 方法用于颠倒数组中元素的顺序。

let person = {name:"张三",age:25,address:"深圳",getName:function(){}}

Object.keys(person).reverse().map((key)=>{

  person[key] // 获取到属性对应的值,对属性进行倒序排列,然后做一些处理

}) 

 四、&& 

有这样一种写法:
this.state.sheetInfo && this.state.sheetInfo.editUrl
上面表达式在sheetInfo存在时,会返回editUrl
 
This is a common way to make sure your function exists before you call it.
expr1 && expr2 Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.
In other words, Javascript does not coerce the operands to boolean values unless it has to.

4 && 5 Returns 5, not true.

五、this.setState({ })

 ES6 允许在大括号里面,直接写入变量和函数,作为对象的属性和方法。这样的书写更加简洁。此时,属性名就是变量名,属性的值就是变量的值。

http://es6.ruanyifeng.com/#docs/object

    this.setState({
      excelEnv  // 等价于 excelEnv:excelEnv
    });

 六、React中onClick()传参

<button onClick={this.handleClick.bind(this, props0, props1, ...}></button>

handleClick(porps0, props1, ..., event) {
    // your code here
}

七、Promise

    //这里介绍新的方法,返回一个 Promise对象
    // 这个Promise对象返回成功后的回调函数带一个 MediaStream 对象作为其参数
    // then()是Promise对象里的方法
    // then()方法是异步执行,当then()前的方法执行完后再执行then()内部的程序
    // 避免数据没有获取到

 八、Lodash库

一个 JavaScript 的实用工具库, 不需要依赖其它库,它提供的许多方法能够简化我们的js代码,例如

function Foo() {
  this.a = 1;
  this.b = 2;
}

Foo.prototype.c = 3;

_.forOwn(new Foo, function(value, key) {
  console.log(key);
});

文档地址:https://www.lodashjs.com/

 九、循环遍历

a、一般会使用for-in来遍历对象的属性的,不过属性需要 enumerable,才能被读取到. for-in 循环只遍历可枚举属性。一般常用来遍历对象,包括非整数类型的名称和继承的那些原型链上面的属性也能被遍历。

b、for-of语句是ES6语法,在可迭代对象(包括 Array,Map,Set,String,TypedArray,arguments 对象等等)上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句。只要是一个iterable的对象,就可以通过for-of来迭代.

var obj = {name:"xx",sex:"yy"};
var arr = [{name:"xx",sex:"yy"},{name:"x2",sex:"y2"}];

for(const i in boj){
  console.log(i) // 输出:name sex
}
for(const i in arr){
  console.log(i) //输出:0 1 即数组的下标
}
for(const i of boj){
  //报错
}

for(const i of arr){
  console.log(i) // 输出{name:"xx",sex:"yy"} {name:"x2",sex:"y2"}
}

 



链接:https://juejin.im/post/5a3a59e7518825698e72376b

 

参考链接:

https://www.cnblogs.com/llcdxh/p/9476347.html

https://stackoverflow.com/questions/12878612/assignment-with-double-ampersand

posted @ 2019-09-28 10:40  sliec  阅读(215)  评论(0编辑  收藏  举报