简体   繁体   English

最好的 javascript 语法糖

[英]Best javascript syntactic sugar

Here are some gems:这里有一些宝石:

Literals:文字:

var obj = {}; // Object literal, equivalent to var obj = new Object();
var arr = []; // Array literal, equivalent to var arr = new Array();
var regex = /something/; // Regular expression literal, equivalent to var regex = new RegExp('something');

Defaults:默认值:

arg = arg || 'default'; // if arg evaluates to false, use 'default', which is the same as:
arg = !!arg ? arg : 'default';

Of course we know anonymous functions, but being able to treat them as literals and execute them on the spot (as a closure) is great:我们当然知道匿名函数,但是能够将它们视为文字并当场执行它们(作为闭包)很棒:

(function() { ... })(); // Creates an anonymous function and executes it

Question: What other great syntactic sugar is available in javascript?问题: javascript 中还有哪些很棒的语法糖?

Getting the current datetime as milliseconds: 获取当前日期时间为毫秒:

Date.now()

For example, to time the execution of a section of code: 例如,要为执行一段代码计时:

var start = Date.now();
// some code
alert((Date.now() - start) + " ms elapsed");

Object membership test: 对象成员测试:

var props = { a: 1, b: 2 };

("a" in props) // true
("b" in props) // true
("c" in props) // false

In Mozilla (and reportedly IE7) you can create an XML constant using: 在Mozilla(以及据称IE7)中,您可以使用以下命令创建XML常量:

var xml = <elem></elem>;

You can substitute variables as well: 您也可以替换变量:

var elem = "html";
var text = "Some text";
var xml = <{elem}>{text}</{elem}>;

Using anonymous functions and a closure to create a private variable (information hiding) and the associated get/set methods: 使用匿名函数和闭包来创建私有变量(信息隐藏)和相关的get / set方法:

var getter, setter;

(function()
{
   var _privateVar=123;
   getter = function() { return _privateVar; };
   setter = function(v) { _privateVar = v; };
})()

Being able to extend native JavaScript types via prototypal inheritance. 能够通过原型继承扩展本机JavaScript类型。

String.prototype.isNullOrEmpty = function(input) {
    return input === null || input.length === 0;
}

Resize the Length of an Array 调整数组长度的大小

length property is a not read only . length属性不是只读的 You can use it to increase or decrease the size of an array. 您可以使用它来增加或减少数组的大小。

var myArray = [1,2,3];
myArray.length // 3 elements.
myArray.length = 2; //Deletes the last element.
myArray.length = 20 // Adds 18 elements to the array; the elements have the empty value. A sparse array.

Use === to compare value and type: 使用===来比较值类型:

var i = 0;
var s = "0";

if (i == s)  // true

if (i === s) // false

Multi-line strings: 多行字符串:

var str = "This is \
all one \
string.";

Since you cannot indent the subsequent lines without also adding the whitespace into the string, people generally prefer to concatenate with the plus operator. 由于您不能在不将空格添加到字符串中的情况下缩进后续行,因此人们通常更喜欢使用plus运算符进行连接。 But this does provide a nice here document capability. 但这确实提供了一个很好的文档功能。

Repeating a string such as "-" a specific number of times by leveraging the join method on an empty array: 通过在空数组上利用join方法,重复一个字符串,如“ - ”特定次数:

var s = new Array(repeat+1).join("-");

Results in "---" when repeat == 3. 当重复== 3时,结果为“---”。

Like the default operator, || 像默认运算符一样, || is the guard operator, && . 是守卫运营商, &&

answer = obj && obj.property

as opposed to 而不是

if (obj) {
    answer = obj.property;
}
else {
    answer = null;
}
var tags = {
    name: "Jack",
    location: "USA"
};

"Name: {name}<br>From {location}".replace(/\{(.*?)\}/gim, function(all, match){
    return tags[match];
});

callback for string replace is just useful. 字符串替换的回调非常有用。

Getters and setters : 吸气剂和二传手

function Foo(bar)
{
    this._bar = bar;
}

Foo.prototype =
{
    get bar()
    {
        return this._bar;
    },

    set bar(bar)
    {
        this._bar = bar.toUpperCase();
    }
};

Gives us: 给我们:

>>> var myFoo = new Foo("bar");
>>> myFoo.bar
"BAR"
>>> myFoo.bar = "Baz";
>>> myFoo.bar
"BAZ"

这不是一个javascript独占,但保存像三行代码:

check ? value1 : value2

Following obj || 关注obj || {default:true} syntax : {default:true}语法:

calling your function with this : hello(neededOne && neededTwo && needThree) if one parameter is undefined or false then it will call hello(false), sometimes usefull 用这个来调用你的函数:hello(neededOne && neededTwo && needThree)如果一个参数未定义或者为false,那么它将调用hello(false), 有时候会有用

更多关于levik的例子:

var foo = (condition) ? value1 : value2;

Javascript 1.6上的Array#forEach

myArray.forEach(function(element) { alert(element); });

In parsing situations with a fixed set of component parts: 在使用一组固定的组件部分解析情境时:

var str = "John Doe";

You can assign the results directly into variables, using the "destructuring assignment" synatx: 您可以使用“解构赋值”synatx将结果直接分配给变量:

var [fname, lname] = str.split(" ");
alert(lname + ", " + fname);

Which is a bit more readable than: 哪个比以下更具可读性:

var a = str.split(" ");
alert(a[1] + ", " + a[0]);

Alternately: 交替:

var [str, fname, lname] = str.match(/(.*) (.*)/);

Note that this is a Javascript 1.7 feature. 请注意,这是一个Javascript 1.7功能。 So that's Mozilla 2.0+ and Chrome 6+ browsers, at this time. 那么这就是Mozilla 2.0+和Chrome 6+浏览器。

Immediately Invoked Arrow function: 立即调用箭头功能:

var test = "hello, world!";
(() => test)(); //returns "hello, world!";

我忘了:

(function() { ... }).someMethod(); // Functions as objects

Create an anonymous object literal with simply: ({}) 简单地创建一个匿名对象文字:({})

Example: need to know if objects have the valueOf method: 示例:需要知道对象是否具有valueOf方法:

var hasValueOf = !!({}).valueOf var hasValueOf = !!({})。valueOf

Bonus syntactic sugar: the double-not '!!' 额外语法糖:双重不是'!!' for converting pretty much anything into a Boolean very succinctly. 几乎任何东西都非常简洁地转换为布尔值。

Assigining the frequently used keywords (or any methods) to the simple variables like ths 将常用的关键字(或任何方法)分配给像这样的简单变量

  var $$ = document.getElementById;

  $$('samText');

I love being able to eval() a json string and get back a fully populated data structure. 我喜欢能够eval()一个json字符串并获得一个完全填充的数据结构。 I Hate having to write everything at least twice (once for IE, again for Mozilla). 我讨厌必须至少写两次(一次用于IE,再次用于Mozilla)。

JavaScript's Date class providing a semi-"Fluent Interface". JavaScript的Date类提供半“Fluent接口”。 This makes up for not being able to extract the date portion from a Date class directly: 这弥补了无法直接从Date类中提取日期部分:

var today = new Date((new Date()).setHours(0, 0, 0, 0));

It's not a fully Fluent Interface because the following will only give us a numerical value which is not actually a Date object: 它不是一个完全流畅的接口,因为以下只给我们一个实际上不是Date对象的数值:

var today = new Date().setHours(0, 0, 0, 0);

Default fallback: 默认回退:

var foo = {}; // empty object literal

alert(foo.bar) // will alert "undefined"

alert(foo.bar || "bar"); // will alert the fallback ("bar")

A practical example: 一个实际的例子:

// will result in a type error
if (foo.bar.length === 0)

// with a default fallback you are always sure that the length
// property will be available.
if ((foo.bar || "").length === 0) 

I love how simple it is to work with lists: 我喜欢使用列表是多么简单:

var numberName = ["zero", "one", "two", "three", "four"][number];

And hashes: 和哈希:

var numberValue = {"zero":0, "one":1, "two":2, "three":3, "four":4}[numberName];

In most other languages this would be quite heavy code. 在大多数其他语言中,这将是非常繁重的代码。 Value defaults are also lovely. 值默认值也很可爱。 For example error code reporting: 例如错误代码报告:

var errorDesc = {301: "Moved Permanently",
                 404: "Resource not found",
                 503: "Server down"
                }[errorNo] || "An unknown error has occurred";

Here's one I just discovered: null check before calling function: 这是我刚发现的一个:在调用函数之前进行null检查:

a = b && b.length;

This is a shorter equivalent to: 这相当于:

a = b ? b.length : null;

The best part is that you can check a property chain: 最好的部分是你可以检查一个房产链:

a = b && b.c && b.c.length;
element.innerHTML = "";  // Replaces body of HTML element with an empty string.

删除元素的所有子节点的快捷方式。

Convert string to integer defaulting to 0 if imposible, 如果不可能,将字符串转换为整数默认为0,

0 | "3" //result = 3
0 | "some string" -> //result = 0
0 | "0" -> 0 //result = 0

Can be useful in some cases, mostly when 0 is considered as bad result 在某些情况下可能很有用,大多数情况下0被视为不良结果

Template literals 模板文字

var a = 10;
var b = 20;
var text = `${a} + ${b} = ${a+b}`;

then the text variable will be like below! 然后文本变量将如下所示!

10 + 20 = 30 10 + 20 = 30

int to string cast int to string cast

var i = 12;
var s = i+"";

optional chaining ( ?. ) can be used so instead of:可选链 ( ?. ) 可以用来代替:

if(error && error.response && error.response.msg){ // do something}

we can:我们可以:

if(error?.response?.msg){ // do something }

more about optional chaining here 更多关于可选链接的信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM