What does a tilde do when it precedes an expression?

前端 未结 5 1529
南方客
南方客 2020-11-22 09:04
var attr = ~\'input,textarea\'.indexOf( target.tagName.toLowerCase() )
           ? \'value\'
           : \'innerHTML\'

I saw it in an answer, and

5条回答
  •  伪装坚强ぢ
    2020-11-22 09:55

    For those considering using the tilde trick to create a truthy value from an indexOf result, it is more explicit and has less magic to instead use the includes method on String.

    'hello world'.includes('hello') //=> true
    'hello world'.includes('kittens') //=> false
    

    Note that this is a new standard method as of ES 2015 so it won't work on older browsers. In cases where that matters, consider using the String.prototype.includes polyfill.

    This feature is also available for arrays using the same syntax:

    ['apples', 'oranges', 'cherries'].includes('apples') //=> true
    ['apples', 'oranges', 'cherries'].includes('unicorns') //=> false
    

    Here is the Array.prototype.includes polyfill if you need older browser support.

提交回复
热议问题