以下是整理的 JavaScript 和 python 的基础区别的整理:
字符串、列表、元组、字典、集合、函数
字符串
声明一个字符串
py
str = '123'
str = "123"
ps:
'''我是注释 '''
a = '我是全局变量'
def init():
a = "嗨,我是局部变量"
init()
print(a) // 我是全局变量
js
str = '123'
str = "123"
当然无疑在js中三个引号 一定是报错的
同时在js中是区分 全局变量和局部变量的
let a = '我是全局变量'
function init(){
let a = '嗨,我是局部变量'
}
init();
console.log(a) // 我是全局变量
a = '我是全局变量'
function init(){
a = '嗨,我是局部变量'
}
init();
console.log(a) // 嗨,我是局部变量
方法对比
py
取得字符串的长度
str = 'abc'
print(len(str)) // 3
字符串首字母大写
str = 'abc'
print(str.title()) // Abc
字符串是否含有某个字母
str = 'abc'
print(str.find('a')) // 0
js
取得字符串的长度
str = 'abc'
console.log(str.length) // 3
字符串首字母大写
str = 'abc'
let newstr = str.replace(/^\S/, s =>s.toUpperCase())
consoe.log(newstr) // Abc
字符串是否含有某个字母
str = 'abc'
console.log(str.indexof('a')) // 0
列表
声明一个列表
py
arr = ['a','b','c','d']
ps: python的声明的数组其实很JavaScript声明是一样的,只是没有声明类型
js
let arr = ['a','b','c','d']
方法对比
py
打印第一个列表元素
arr = ['a','b','c','d']
print(arr[0]) // a
打印非第一个元素剩余列表元素
arr = ['a','b','c','d']
print(arr[1:]) // ['b','c','d']
打印倒数第二个元素
arr = ['a','b','c','d']
print(arr[-2]) // c
js
打印第一个列表元素
let arr = ['a','b','c','d']
console.log(arr[0]) // a
打印非第一个元素剩余列表元素
let arr = ['a','b','c','d']
console.log(arr.slice(1)) // ['b','c','d']
打印倒数第二个元素
let arr = ['a','b','c','d']
console.log(arr[arr.length - 2]) // c
ps:
想要在python得到每个值,也是需要循环的,但是python支持的循环的方法只有、 for in
\ while
在JavaScript中支持数组循环的方法就有很多了、for\for in\ map\foreach\ map\...
dasd