document.write()
:将内容写入html文档console.log()
:将内容写入控制台alert()
:弹窗JS是弱类型语言,变量无类型
number
:数字。整数、浮点数、NaNstring
:字符串。
'Hello'
"Hello"
`Hello ${name}`
boolean
:布尔值。object
:对象。
[1, 2, 3]
function() {}
或箭头函数 () => {}
new Date()
/abc/
null
:空值。
undefined
:未定义。
使用typeof运算符可以判断变量的数据类型。
+
, -
, *
, /
, %
=
, +=
, -=
, *=
, /=
==
, ===
, !=
, !==
, <
, >
, <=
, >=
==
:值相等,不考虑类型。===
:值相等,且类型相同。!=
:值不相等。!==
:值不相等,或类型不同。 var age=18;
var age1="18";
alert(age == age1); // true, 因为值相等
alert(age === age1); // false, 因为类型不相等
alert(age != age1); // false, 因为值相等
alert(age !== age1); // true, 因为类型不相等
&&
, ||
, !
&
, |
, ^
, ~
, <<
, >>
, >>>
condition ? expr1 : expr2
Number()
:将字符串转换为数字。parseInt()
:将字符串转换为整数。parseFloat()
:将字符串转换为浮点数。 var str1 = "123";
var str2 = "12A3";
var str3 = "A123";
var str4 = "12.3";
var num = Number(str1); // 123
alert(num); // 输出 "123"
num = parseInt(str2); // 12
alert( num); // 输出 "12"
num = parseInt(str3); // NaN
alert( num); // 输出 "NaN"
num = parseFloat(str4); // 12.3
alert( num); // 输出 "12.3"
num = parseInt(str4); // 12
alert(num); // 输出 "12"
+
:将字符串转换为数字。例: var str = "12.3";
var num = +str; // 12.3
alert(typeof num); // 输出 "number"
toString()
:将数字转换为字符串。String()
:将数字转换为字符串。Boolean()
:将其他类型转换为布尔值。!!
:将其他类型转换为布尔值。Number
:0和NaN为false,其余为trueString
:空字符串为false,其余为truenull
和undefined
:均转为false var num = 123;
var str = "12.3";
var bool = true;
var obj = { name: "张三" };
alert(Boolean(num)); // 输出 "true"
alert(Boolean(str)); // 输出 "true"
alert(Boolean(bool)); // 输出 "true"
alert(Boolean(obj)); // 输出 "true"
alert(Boolean(null)); // 输出 "false"
alert(Boolean(undefined)); // 输出 "false"
用法与Java
相同
function functionName(parameters) {
// 函数体
}
const functionName = function(parameters) {
// 函数体
};
const functionName = (parameters) => {
// 函数体
};
function greet(name = "Guest") {
console.log(`Hello, ${name}!`);
}
greet(); // 输出 "Hello, Guest!"
greet("Alice"); // 输出 "Hello, Alice!"
...
表示剩余参数,将剩余参数收集为数组。 function sum(a, b, ...rest) {
console.log(a, b, rest);
}
sum(1, 2, 3, 4, 5); // 输出 "1 2 [3, 4, 5]"
...
将数组展开为单独的参数。 function sum(a, b, c) {
console.log(a, b, c);
}
const arr = [1, 2, 3];
sum(...arr); // 输出 "1 2 3"
{}
解构参数。 function printPerson({ name, age }) {
console.log(`Name: ${name}, Age: ${age}`);
}
const person = { name: "张三", age: 18 };
printPerson(person); // 输出 "Name: 张三, Age: 18"
//方法一
var arr1 = new Array(1,2,3);
//方法二
var arr2 = [1, 2, 3];
console.log(arr1[0]);
arr1.length=5;
arr1[4]='A';
console.log(arr1);
length
属性会获得数组的长度undefined
push()
:向数组末尾添加元素。pop()
:删除数组末尾元素。//push
var arr1 = [1, 2, 3, 4, 5];
arr1.push('A');
console.log(arr1); // 输出 [1, 2, 3, 4, 5, 'A']
//pop
arr1.pop();
console.log(arr1); // 输出 [1, 2, 3, 4, 5]
unshift()
:向数组开头添加元素。shift()
:删除数组开头元素。//unshift
var arr1 = [1, 2, 3, 4, 5];
arr1.unshift('A');
console.log(arr1); // 输出 ['A', 1, 2, 3, 4, 5]
//shift
arr1.shift();
console.log(arr1); // 输出 [1, 2, 3, 4, 5]
slice()
:提取数组的一部分。 var arr1 = [1, 2, 3, 4, 5];
var newArr = arr1.slice(1, 4); // 从索引1开始提取到索引4(不包含)
console.log(newArr); // 输出 [2, 3, 4]
splice(Index, DeleteCount)
:删除、替换或添加数组元素。 arr1.splice(1,2); // 从索引1开始删除2个元素
console.log(arr1); // 输出 [1, 3, 4, 'A']
arr1.splice(1,0,'B'); // 在索引1处插入'B'
console.log(arr1); // 输出 [1, 'B', 3, 4, 'A']
forEach(function(item,index,arr))
:遍历数组有值的元素,不会遍历未赋值的元素。每遍历一个元素,会调用一次函数。arr1.forEach(function(item){
console.log(item);
})
map()
:创建新数组,每个元素都是调用函数后的结果。 var newArr = arr1.map(function(item) {
return item * 2; // 每个元素乘以2
});
console.log(newArr); // 输出 [2, 6, 8, 'A']
//方法一
var str1 = new String('123');
//方法二
var str2 = '123';
console.log(str1);
length
:字符串的长度
charAt(index)
:返回指定索引的字符。var str2 = '123';
console.log(str2.charAt(1)); // 输出 '2'
indexOf(substring)
:返回匹配到第一个子字符串的索引。var str2 = '123';
console.log(str2.indexOf('23')); // 输出 1
lastIndexOf(substring)
:返回匹配的最后一个子字符串的索引。var str2 = '12323';
console.log(str2.lastIndexOf('23')); // 输出 3
substring(start, end)
:返回子字符串。var str2 = '123';
console.log(str2.substring(1, 3)); // 输出 '23'
slice(start, end)
:返回子字符串。var str2 = '123';
console.log(str2.slice(1, 3)); // 输出 '23'
replace(search, replacement)
:替换字符串中的子字符串。var str2 = '123';
console.log(str2.replace('23', '45')); // 输出 '145'
split(separator)
:将字符串拆分为数组。var str2 = '123';
console.log(str2.split('')); // 输出 ['1', '2', '3']
trim()
:删除字符串开头和结尾的空格。var str2 = ' 123 ';
console.log(str2.trim()); // 输出 '123'
自定义对象:
var person = {
name: "张三",
age: 18,
sayName: function() {
console.log("我的名字是:" + this.name);
}
/*或
sayName() {
console.log("我的名字是:" + this.name);
}
*/
};
alert(person.name); // 输出 "张三"
person.sayName(); // 输出 "我的名字是:张三"
JSON对象
var jsonObj = {
"name": "张三",
"age": 18,
"isStudent": false,
"courses": ["数学", "英语"],
"address": {
"city": "北京",
"zipCode": "100000"
}
};
JSON.parse(jsonString)
:将JSON字符串解析为JavaScript对象。var jsonString = '{"name":"张三","age":18,"isStudent":false}';
var obj = JSON.parse(jsonString);
console.log(obj.name); // 输出 张三
JSON.stringify(obj)
:将JavaScript对象转换为JSON字符串。var obj = {name: "张三", age: 18, isStudent: false};
var jsonString = JSON.stringify(obj);
console.log(jsonString); // 输出 {"name":"张三","age":18,"isStudent":false}
BOM(Browser Object Model)是浏览器对象模型,用于操作浏览器窗口和文档。
window
对象是BOM的核心,代表浏览器窗口。
window
对象包含浏览器窗口的属性和方法。window
对象的属性和方法可以直接调用,不需要使用window
前缀。window.location
:获取或设置当前文档的URL。window.history
:访问浏览器历史记录。window.navigator
:获取浏览器信息。window.alert(message)
:显示警告信息。window.prompt(message, defaultValue)
:显示输入对话框。window.confirm(message)
:显示确认对话框,确认返回true,取消返回false。window.open(url, windowName, features)
:打开新窗口。window.close()
:关闭当前窗口。window.setTimeout(function, delay)
:设置定时器,在指定时间后执行函数,执行一次。setTimeout(function() {
console.log('定时器执行');
}, 2000); // 2000毫秒后执行
window.setInterval(function, delay)
:设置重复定时器,在指定时间间隔后重复执行函数。 setInterval(function() {
console.log('定时器执行');
}, 1000); // 每1000毫秒执行一次
Location
对象表示地址栏。
location.href
:获取或设置当前文档的URL。alert(location.href); // 输出当前URL
location.href = 'https://www.example.com'; // 跳转到新URL
DOM(Document Object Model)是文档对象模型,用于操作文档的内容。
document.getElementById(id)
:根据ID获取元素。<div id="myElement">Hello Worlddiv>
<script>
var element = document.getElementById('myElement');
console.log(element); // 输出 Hello World
script>
document.getElementsByClassName(className)
:根据类名获取元素集合,返回所有类名相同的元素。<div class="myClass">Hello Worlddiv>
<script>
var elements = document.getElementsByClassName('myClass');
console.log(elements); // 输出 Hello World
script>
document.getElementsByTagName(tagName)
:根据标签名获取元素集合,返回所有标签名相同的元素。<div class="myClass">Hello Worlddiv>
<script>
var elements = document.getElementsByTagName('div');
console.log(elements); // 输出 Hello World
script>
document.getElementsByName(name)
:根据元素的name属性获取元素集合,返回所有name属性相同的元素。<div class="myClass">Hello Worlddiv>
<script>
var elements = document.getElementsByName('div');
console.log(elements); // 输出 Hello World
script>
div
元素的内容:element.innerHTML
:获取或设置元素的HTML内容。element.textContent
:获取或设置元素的文本内容。<div class="myClass">Hello Worlddiv>
<script>
var element = document.getElementsByClassName('myClass')[0];
console.log(element.innerHTML); // 输出 Hello World
console.log(element.textContent); // 输出 Hello World
element.innerHTML = 'Hello JS'; // 修改HTML内容
script>
更多操作详见:
事件监听是指在特定事件发生时执行指定的函数。
<button onclick="alert('按钮被点击')">点击我button>
<button oncliick="f()">点击我button>
<script>
function f() {
alert('按钮被点击');
}
script>
document.getElementById('myButton').addEventListener('click', function() {
alert('按钮被点击');
});
onclick
:点击事件,当用户点击元素时触发。onblur
:失去焦点事件,当元素失去焦点时触发。onfocus
:获得焦点事件,当元素获得焦点时触发。onchange
:改变事件,当元素的值发生改变时触发。onsubmit
:提交事件,当表单提交时触发。onreset
:重置事件,当表单重置时触发。onselect
:选择事件,当用户选择文本时触发。onmouseover
:鼠标悬停事件,当鼠标悬停在元素上时触发。onmouseout
:鼠标移出事件,当鼠标移出元素时触发。onmousedown
:鼠标按下事件,当用户按下鼠标按钮时触发。onmouseup
:鼠标松开事件,当用户松开鼠标按钮时触发。onkeydown
:键盘按下事件,当用户按下键盘键时触发。onkeyup
:键盘松开事件,当用户松开键盘键时触发。onkeypress
:键盘按下事件,当用户按下键盘键时触发。