对所有javascript类型使用in运算符

时间:2018-10-24 02:04:25

标签: javascript

对javascript中的每种类型执行以下操作的正确方法是什么:

import string

def uniques():
    file = open("test.txt", "r")
    dic = {}
    data = file.read().replace('\n', ' ')
    strip = removePunctuation(data)
    lines = strip.split(' ')
    print(strip)
    print(lines)

    for item in lines:

        #this produces an error of unhashable type: 'list'
        if lines in dic:
            dic[item] = dic[item] + 1
        else:
            print("else ran")
            dic[item] = 1

    for item in dic:
        print(item, dic[item])
        print("There are " + str(len(dic)) + " items in the dictionary")

def removePunctuation(text):
    text = text.strip()
    return text.rstrip(string.punctuation)

uniques()

我想为上述每个可迭代对象返回一个布尔值。我知道// string "h" in "hello" // array "hello" in ["hello", "abc", "yes"] // obj "hello" in {"hello": "new"} 可以正常使用,但是其他所有方法最简单的方法是什么?

1 个答案:

答案 0 :(得分:2)

对于字符串和数组,请使用.includes

console.log('hello'.includes('h'));
console.log(["hello", "abc", "yes"].includes('hello'));

请注意,.includes是ES6,因此还包括一个polyfill以支持较旧的浏览器:1 2