JavaScript基本知識-W3school-1

本文详细梳理了JavaScript的基础知识点,包括JavaScript的位置、输出方式、大小写敏感、语句、操作符、数据类型、函数、对象、作用域、字符串和字符串方法。强调了document.write()在页面加载后的使用会删除现有HTML,以及区分undefined和null的重要性,并提醒避免将字符串、数字和布尔值声明为对象,以保持代码效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Javascript基础知识整理

1. javascript where to

a) header or body

<script></script>

b) header:external files

 <script src="myScript.js"></script>

2. JavaScript Output

Writing into an alert box, using window.alert().
Writing into the HTML output using document.write().
Writing into an HTML element, using innerHTML.
Writing into the browser console, using console.log().

** Using document.write() after an HTML document is fully loaded, will delete all existing HTML

3. JavaScript is Case Sensitive

Camel Case: LastName

4. JavaScript Statements

If a JavaScript statement does not fit on one line, the best place to break it, is after an operator:

document.getElementById("demo").innerHTML =
      "Hello Dolly.";

[** You can also break up a code line within a text string with a single backslash:]

document.getElementById("demo").innerHTML = "Hello \
      Dolly!";

[**]The \ method is not a ECMAScript (JavaScript) standard.
Some browsers do not allow spaces behind the \ character.
The safest (but a little slower) way to break a long string is to use string addition(+)

5. JavaScript Operators

a)JavaScript Assignment Operators

OperatorExampleSame As
=x = yx = y
+=x += yx = x + y
-=x -= yx = x - y
*=x *= yx = x * y
/=x /= yx = x / y
%=x %= yx = x % y
**Exponentiation

~
b)JavaScript Comparison and Logical Operators [JS Comparisons]

OperatorDescription
===equal value and equal type
!==not equal value or not equal type

~
c)JavaScript Type Operators [JS Type Conversion]

OperatorDescription
typeofReturns the type of a variable
instanceofReturns true if an object is an instance of an object type

6. JavaScript Data Types

a)

var x = 16 + 4 + "Volvo";   //[20Volvo]
var x = "Volvo" + 16 + 4;   //[Volvo164]

b)JavaScript Numbers

var y = 123e5;      // 12300000
var z = 123e-5;     // 0.00123

c)JavaScript Arrays

var cars = ["Saab", "Volvo", "BMW"]; 

d)JavaScript Objects

var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

e)The typeof Operator

 typeof "John"                // Returns string 
 typeof 3.14                  // Returns number
 typeof false                 // Returns boolean
 typeof [1,2,3,4]             // Returns object [***]
 typeof {name:'John', age:34} // Returns object 

f)Undefined
In JavaScript, a variable without a value, has the value undefined. The typeof is also undefined.

var person;          // Value is undefined, type is undefined
person = undefined;  // Value is undefined, type is undefined

g)Empty Values
An empty value has nothing to do with undefined.
An empty string variable has both a value and a type.

 var car = "";                // The value is "", the typeof is string

h)Null
In JavaScript null is “nothing”. It is supposed to be something that doesn’t exist.
Unfortunately, in JavaScript, the data type of null is an object.
You can consider it a bug in JavaScript that typeof null is an object. It should be null.

 var person = null;           // Value is null, but type is still an object

i)Difference Between Undefined and Null

typeof undefined              // undefined
typeof null                   // object
null === undefined            // false
null == undefined             // true

7. JavaScript Functions

a)Accessing a function without () will return the function definition
example:

 function toCelsius(fahrenheit) {
     return (5/9) * (fahrenheit-32);
 }
 document.getElementById("demo").innerHTML = toCelsius;
 //function toCelsius(f) { return (5/9) * (f-32); }

8. JavaScript Objects

a)Accessing Object Properties
objectName.propertyName or objectName[“propertyName”]

b)Accessing Object Methods
objectName.methodName()

example:

var person = {
           firstName: "John",
           lastName : "Doe",
           id       : 5566,
           fullName : function() {
              return this.firstName + " " + this.lastName;
           }
       };
document.getElementById("demo").innerHTML = person.fullName; 
// [If you access it without (), it will return the function definition]

~
c)[**]Do Not Declare Strings, Numbers, and Booleans as Objects!
They complicate your code and slow down execution speed.

9. JavaScript Scope

a)Automatically Global
If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.
This code example will declare a global variable carName, even if the value is assigned inside a function.
example:

// code here can use carName as a global variable
document.getElementById("demo").innerHTML = "I can display " + carName;
function myFunction() {
     carName = "Volvo";
}
//[I can display Volvo]
//[**Do NOT create global variables unless you intend to.]

b)Global Variables in HTML
With JavaScript, the global scope is the complete JavaScript environment.
In HTML, the global scope is the window object. All global variables belong to the window object.
eg:

<script>
    var carName = "Volvo";
    // code here can use window.carName
    document.getElementById("demo").innerHTML = "I can display " + window.carName;
</script>

10. Javascript Strings

a)Strings Can be Objects

var x = "John";            
var y = new String("John");
var z = new String("John");
// (x == y) is true because x and y have equal values 
// (x === y) is false because x and y have different types (string and object)
// (y == z) is false because y and z are different objects
// (y == y) is true because both are the same object

[** Don’t create strings as objects. It slows down execution speed.
The new keyword complicates the code. This can produce some unexpected results]
[** JavaScript objects cannot be compared.]

11. JavaScript String Methods

a)
str.indexOf(searchValue[, fromIndex])
str.lastIndexOf(searchValue[, fromIndex]) [**fromIndex から検索を始め、逆方向に検索されます。]
str.search(regexp)
Both the indexOf(), and the lastIndexOf() methods return -1 if the text is not found.

b)The slice() Method

var str = "Apple, Banana, Kiwi";
var res = str.slice(7,13);   //[Banana]
var res = str.slice(-12,-6); //[Banana]
var res = str.slice(7);      //[Banana, Kiwi]
var res = str.slice(-12);    //[Banana, Kiwi]
// [** Negative positions do not work in Internet Explorer 8 and earlier.]

c)The substring() Method
substring() is similar to slice().
The difference is that substring() cannot accept negative indexes.

d)The substr() Method
substr() is similar to slice().
The difference is that the second parameter specifies the length of the extracted part.

 var str = "Apple, Banana, Kiwi";
 var res = str.substr(7,6);    //[Banana]

e)Replacing String Content

str = "Please visit Microsoft!";
var n = str.replace("Microsoft","W3Schools");
//[**]By default, the replace() function replaces only the first match. 
//[To replace all matches, use a regular expression with a g flag (for global match):]
str = "Please visit Microsoft!";
var n = str.replace(/Microsoft/g,"W3Schools");
//[**The replace() method does not change the string it is called on. It returns a new string. ]

f)toUpperCase() toLowerCase()

g)The concat() Method

var text = "Hello" + " " + "World!";
var text = "Hello".concat(" ","World!");

h)Extracting String Characters
2 safe methods :
charAt(position)
charCodeAt(position) // returns the unicode of the character at a specified index in a string

var str = "HELLO WORLD";
str.charAt(0);            // returns H 
str.charCodeAt(0);         // returns 72 

Accessing a String as an Array is Unsafe:str[0];

i)Converting a String to an Array
split()
If the separator is omitted, the returned array will contain the whole string in index [0].
If the separator is “”, the returned array will be an array of single characters.

var txt = "Hello";       // String
txt.split("");           //["H","e","l","l","o"]
txt.split();             //["Hello"]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值